GraphQL
GraphQL is a powerful query language for APIs and a runtime for executing those queries with your data.
Developed by Meta in 2012, it was created to address the need for more flexibility and efficiency in client-server interactions. It allows clients to request exactly what they need and nothing more, where queries describe the data to be returned. This significantly reduces the amount of data transferred between client and server and the number of calls to get it, unlike REST where you might call multiple endpoints to get the same data.
The GraphQL Schema
At its core, a schema is composed of custom types, such as Patient, Appointment, etc. These types define the fields that can be queried on that type, such as fistName or startDate, and each field is associated with a specific data type (e.g., String, Int, Boolean).
The schema also identifies special types for Query and Mutation which are entry points for the data retrieval and data manipulation operations, respectively. For example, a Query type might include fields like patients or appointments, each associated with a corresponding return type.
Queries are used to read data from a GraphQL API, where you describe the data you want returned in one query.
Mutations are used to update in a GraphQL API. The equivalent of a REST POST.
Subscriptions can be used to be notified of for real-time events in the system.
API Request
Initiating a query on the API essentially amounts to a HTTP Post to the GraphQL endpoint with a JSON payload containing the query. See the Query examples section for some sample queries.
info
Replace <TOKEN> for the JWT access token you get after logging in with your API key and secret.
Using cURL
Using JavaScript's fetch
API Response
When parsing a GraphQL JSON response, there are two key fields to focus on. The first is data, which will have the data in the format you requested it in your query. The other is errors, which may have errors returned by the API during processing. A response may have both fields in a single response. Use error handling to gracefully handle and log any errors while accessing specific fields from the data object as per your application's needs.
An example from spec.graphql.org
{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [{ "line": 6, "column": 7 }],
"path": ["hero", "heroFriends", 1, "name"]
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}
}