Software Engineering :: API :: Architectural Style :: GraphQL :: Training :: Interacting with GraphQL APIs
⪼ Made with 💜 by Polyglot.
Programatically interacting with GraphQL servers is very similar to interacting with any other REST or HTTP-based API; you send an HTTP POST request to the desired GraphQL endpoint (usually /graphql
). The body of the request is a JSON object with a single key of either query
or mutation
. The value at this key is your GraphQL query
or mutation
as a string.
In other words; any simple HTTP client can be used to interact with GraphQL servers. This means, you can use cURL
, fetch
, Postman (or any of the alternatives); and don't forget that your favorite programming language probably has a capable HTTP client within its standard library.
To demonstrate this point, we'll look at the Countries GraphQL API. This API provides data about countries. The first query we'll issue to this API is a query to retrive a list of countries. Ideally, we want the country's name, it's abbreviation, and an image of the country's flag.
In order to accomplish this task, we need to know what object types and fields are available to query at the GraphQL service.
Generally, public GraphQL servers provide a GraphQL Explorer; A GraphQL Explorer is an interactive web application for composing, testing, and validating queries against its associated GraphQL API; most explorers offer features such as code autocomplete, syntax highlighting, and integrated schema documentation.
The GraphQL Explorer is powered by an introspection system which is provided by every GraphQL service. This allows a client to simply ask the GraphQL service directly, without the need for a graphical explorer, "which types are available?". This is accomplished by querying the __schema
field. This field is always available on the Root Query type. Keep in mind, private GraphQL APIs will typically have introspection disabled in production.
The following introspection query will return the fields availabale:
query SchemaIntrospection {
__schema {
queryType {
fields {
name
description
}
}
}
}
query CountriesList {
countries {
code
name
emoji
}
}
GraphQL Query with the cURL program:
curl --location 'https://countries.trevorblades.com/graphql' \
--header 'Content-Type: application/json' \
--data '{ "query": "query GetCountry { country(code: \"US\") { name native capital emoji currency languages { code name } }}"}'
Step 1: Navigate to the Schema Documentation
Once you've navigated to the documentation page, locate the list of objects available to query.
For this example, the object I care about is Country.
- How to Retrieve a GraphQL Schema
- Why You Should Disable GraphQL Introspection In Production – GraphQL Security
- GraphQL introspection and introspection queries
- GraphQL Introspection
- GraphQL Voyager
- GraphQL :: Courses :: Learning GraphQL :: 4. Creating a GraphQL Server Schema