Queries
Introduction
GraphQL is a query language for APIs. This sheet covers queries, HTTP requests, mutations, and schema types.
- GraphQL (graphql.org)
- GraphQL specification (spec.graphql.org)
- GraphQL learn (graphql.org)
Basic query
Nesting
Lists
{ friends { name } }
Result
{ friends: [ { name: "Luke Skywalker" },
{ name: "Han Solo" },
{ name: "R2D2" } ] }
GraphQL queries look the same for both single items or lists of items.
See: List type
Lookups
{
hero(id: "1000") { id name }
}
Result
{ hero: { id: "1000",
name: "Luke Skywalker" } }
See: Arguments
Aliases
{
luke: hero(id: "1000") { name }
han: hero(id: "1001") { name }
}
Result
{ luke: { name: "Luke Skywalker" },
han: { name: "Han Solo" } }
See: Field alias
Operation names and variables
Query
query FindHero($id: ID!) {
hero(id: $id) { name }
}
Variables
{ id: "1000" }
The operation type is required to declare variables; naming it is optional but helps debugging.
Mutations
Query
mutation CreateReview(
$review: ReviewInput!
) {
createReview(review: $review) { id }
}
Variables
{ review: { stars: 5 } }
Result
{ createReview: { id: 5291 } }
Only top-level Mutation fields may cause side effects; they run in series.
See: Mutation
Multiple types
{
search(q: "john") {
id
... on User { name }
... on Comment {
body
author { name }
}
}
}
Great for searching.
See: Inline fragments
Over HTTP
GET requests
const q = encodeURIComponent(
'{ me { name } }'
)
fetch(`http://myapi/graphql?query=${q}`)
See: GET requests
POST requests
fetch('http://myapi/graphql', {
body: JSON.stringify({
query: '...',
operationName: '...',
variables: { ... }
})
})
See: POST requests
Schema
Basic schemas
type Query {
me: User
users(limit: Int): [User]
}
type User {
id: ID!
name: String
}
See: Type language
Built in types
Scalar types
| Type | Description |
|---|---|
Int | Integer |
Float | Float |
String | String |
Boolean | Boolean |
ID | ID |
Type definitions
| Definition | Description |
|---|---|
scalar | Scalar type |
type | Object type |
interface | Interface type |
union | Union type |
enum | Enumerable type |
input | Input object type |
Type modifiers
| Syntax | Description |
|---|---|
String | Nullable string |
String! | Required string |
[String] | List of strings |
[String]! | Required list of strings |
[String!]! | Required list of required strings |
See: Scalar types
Mutations
type Mutation {
users(params: ListUsersInput): [User]!
}
Interfaces
interface Entity {
id: ID!
}
type User implements Entity {
id: ID!
name: String
}
See: Interface types
Enums
enum DIRECTION {
LEFT
RIGHT
}
type Root {
direction: DIRECTION!
}
See: Enum types
Unions
type Artist { ··· }
type Album { ··· }
union Result = Artist | Album
type Query {
search(q: String): [Result]
}
See: Union types
0 Comments for this cheatsheet. Write yours!