Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

perl and GraphQL example

by Krillian (Acolyte)
on Oct 14, 2020 at 11:29 UTC ( #11122825=perlquestion: print w/replies, xml ) Need Help??

Krillian has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am trying to figure out how to post a request from perl to GraphQL API. I couldn't find any tutorials online. As far as I understand I can use this cpan module https://metacpan.org/pod/GraphQL

But I am still confused as to how to do it exactly. If someone could respond with an example, would be very much appreciated.

Here is what I am trying to do: Send a post request to the API with a authentication header and body with query and graphql variables. I should then get a response in JSON, which I will process (this part I understand how to do).

Thank you very much in advance!

Replies are listed 'Best First'.
Re: perl and GraphQL example
by Krillian (Acolyte) on Oct 15, 2020 at 09:52 UTC
    For anyone interested, this is what I ended up doing. Any suggestions are very welcome

    This is for the waveapps api

    #!/usr/bin/env perl require LWP::UserAgent; use JSON; use Data::Dumper; my $uri = 'https://gql.waveapps.com/graphql/public'; my $json = <<'EOF'; {"query": "query ($businessId: ID!, $page: Int!, $pageSize: Int!) { business(id: $businessId) { id products(page: $page, pageSize: $pageSize) { edges { node { id name description unitPrice defaultSalesTaxes { id name abbreviation rate } } } } } } ", "variables" : { "businessId": "ENTER_BUSINESS_ID_HERE", "page": 1, +"pageSize": 500 } } EOF # remove newlines $json =~ s/(\n|\r)//g; my $req = HTTP::Request->new( 'POST', $uri ); $req->header( 'Content-Type' => 'application/json', 'Authorization' => + 'Bearer ENTER_BEARER_TOKEN_HERE'); $req->content( $json ); my $lwp = LWP::UserAgent->new; my $res = $lwp->request( $req ); $data = decode_json($res->content); print Dumper($data);
Re: perl and GraphQL example
by perlfan (Vicar) on Oct 14, 2020 at 16:39 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11122825]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2020-10-31 11:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (288 votes). Check out past polls.

    Notices?