How to Curl a GraphQL API?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to Curl a GraphQL API?

Posted on: March 19, 2019

In the last few months, I have been implementing a GraphQL server in TypeScript and NodeJS using Apollo. You can build your query with the playground and see the result immediately. At the top, a "Curl" button generates a Curl command. However, it writes the command with many options that are not required.

The generated command line has "--compressed" and "--data-binary" which might be fine for few people but in some case, these options were not available. I figure out that you do not need to provide them and still be able to invoke the GraphQL server.

1curl 'http://retracted.net/playground' \\
2 -H 'Accept-Encoding: gzip, deflate, br' \\
3 -H 'Content-Type: application/json' \\
4 -H 'Accept: application/json' \\
5 -H 'Connection: keep-alive' \\
6 -H 'DNT: 1' \\
7 -H 'Origin: http://retracted.net' \\
8 --data-binary '{"query":"{\\n org(orgId: 0) {\\n nameLong,\\n nameShort\\n }\\n}\\n"}' \\
9 --compressed

The generated Curl command line for GraphQL has many headers that can be removed. In my case, I needed to add the authorization header because the service is private.

1curl \\
2 -X POST \\
3 -H "Content-Type: application/json" \\
4 -H "authorization: Bearer xxx" \\
5 --data '{"query":"{\\n org(orgId: 0) {\\n nameLong,\\n nameShort\\n }\\n}\\n"}' \\
6 http://retracted.net/api

However, even with the additional header, the command is more straightforward. Instead of requesting the data with --data-binary, it is possible to query with --data. The compression can be removed if the accept-encoding is not specified. The content we will receive is of JSON type, hence we need to specify the content-type

In conclusion, this was a short essay on how to use Curl with GraphQL. It can be handy if you have internal tools that mimic Curl but without the more advanced options like compression or binary data.