14
loading...
This website collects cookies to deliver better user experience
SELECT * from users
for your database. Instead, GraphQL syntax defines how to ask for data from your API. the syntax of a GraphQL query looks like this -query getUsers{
users {
firstname
}
}
QL
in GraphQL means a query language for your API, not database. /users/{id}/
. If we use a curl request to make a call and pass in id
of a user, it will look like this -curl \
-H "Content-Type: application/json" \
https://www.example.com/api/users/123`
The "GET" operation of REST is done by "Query" in GraphQL.
We don't have a separate endpoint for users
in GraphQL. Every request is sent to /graphql
endpoint.
In order to describe what data we are interested in, we pass the relevant parameters to "Query" operation and describe which Query we are interested in. A GraphQL API may support something like "getUsers" Query, which is a query we can use to get users.
curl \
-X POST \
-H "Content-Type: application/json" \
--data '{ "query": "{ user(id:123 ) { name } } " }' \
https://www.example.com/graphql
GET /user/{id}
is mapped to getUser(String id)
. getUser
defines what data is passed if this endpoint is called. This resource implementation will also call any downstream operation if need be - other APIs or fetch directly from the database.type Query {
getUser(id: $String!)
}
getUser
query is defined by a function called resolvers. Resolvers define what data should be returned when a field is called. Every query is mapped to a resolver. A resolver function can call any API or data sources. Our resolver can be written like this -getUser(args){
const { id } = args;
//fetch from database / API
}
getUser
query, they will get back data like this -{
"data" : {
"name": "Sample name"
}
}
REST | GraphQL |
---|---|
REST has multiple endpoints. | GraphQL has one endpoint - /graphql |
REST APIs support PUT, GET, POST, DELETE, PATCH | GraphQL supports Query, Mutation, Subscription |
REST endpoints are populated by resource implementations | GraphQL fields are populated by resolvers |
200 , 400 , 500 level status codes | 200 level status codes |
Often times, roundtrips need to be done in order to fetch complete data | You can fetch multiple fields therefore fetch all the data you need with one requestt |
Shape of the data is determined by the server | Shape of the data is determined by the client calling the API. |
graphql
, and in addition to making the call to the API endpoint and passing desired parameters, we also need to provide exactly what fields we want to access.