HomeToolsAbout a20k

Client Requests

Client Request Basics

All GraphQL requests are POST method request.

Defaults to endpoint of /graphql.

Because of this, if you make a POST fetch request to /graphql endpoint with the following request, GraphQL will respond with expected payload:

options = { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ query:` { title } ` }) } fetch('/graphql', options);

Client Input

Client query can define inputs (arguments).

# query argument variable starts with a $ sign # it is typed query getUnits($ID: String!) { # query argument is passed to the query getUnits(id: $ID) { id name createdDatetime updatedDatetime } }

This would add another field to the request:

options = { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ query:` { title } ` variables: { // also used for mutation payload "ID": "a731-21" } }) } fetch('/graphql', options);

Client Querying is Flexible

Client can request for flexible information it wants from the graph

  • Meaning, the client can define what will be scoped to the particular return/response

Backend will have to support all possible fields for query in case the frontend requests for it (any permutation)

# Mutation mutation submitInput($mutationInput: GraphqlInputType!) { submitInput(input: $mutationInput) { id name inputMetric createdDatetime updatedDatetime # there could be a lot more fields in existence } } # Mutation payload { "input": { "name": "Sam", "id": "abc123" } }

Error Handling

Do not prematurely return, throw an explicit error such as 404

  • Prematurely returning a data will result in type drift instead (since it is a partial result)

Non-null argument in querying

The Non-Null type modifier (!) can also be used when defining arguments for a field, which will cause the GraphQL server to return a validation error if a null value is passed as that argument, whether in the GraphQL string or in the variables.

# query definition in front end query DroidById($id: ID!) { droid(id: $id) { name } } # client query param { "id": null } # returned result from GQL server { "errors": [ { "message": "Variable \"$id\" of non-null type \"ID!\" must not be null.", "locations": [ { "line": 1, "column": 17 } ] } ] }
© VincentVanKoh