GraphQL
Quick start
GraphQL from zero: what it is, and a working API in five minutes.
What is GraphQL?
With a normal REST API the server decides what each URL returns. To show a book with its author and reviews you often make three calls (/books/1, /authors/7, /books/1/reviews) and receive fields you did not need. With GraphQL there is one URL, and the client sends a query that describes exactly the data it wants. The server answers with exactly that shape, in one round trip.
Everything in GraphQL is described by a schema: the list of types and what you can ask for. There are three kinds of operation:
| Operation | Like REST's | Purpose |
|---|---|---|
| query | GET | read data |
| mutation | POST / PUT / DELETE | change data |
| subscription | WebSocket | receive live updates |
Build a small API
1. The schema. It lists the types and the entry points (Query, Mutation):
val SCHEMA = """
type Author { id: ID! name: String! }
type Book { id: ID! title: String! author: Author }
type Query { books: [Book!]! book(id: ID!): Book }
type Mutation { addBook(title: String!, authorId: ID!): Book! }
"""String! means "never null"; [Book!]! means "a list that is never null, of books that are never null"; ID is an identifier.
2. The resolvers. A resolver is the code that answers a field. In Kest it is a class marked @Resolver, declared exactly like a controller: no @Injectable, and it is listed in the module's controllers:
data class Author(val id: String, val name: String)
data class Book(val id: String, val title: String, val authorId: String)
@Resolver
class LibraryResolver(private val library: LibraryService) {
@Query fun books(): List<Book> = library.allBooks()
@Query fun book(id: String): Book? = library.find(id) // parameters bind BY NAME to the field's arguments
@Mutation fun addBook(title: String, authorId: String): Book = library.add(title, authorId)
@ResolveField("Book") fun author(book: Book): Author? = library.author(book.authorId) // fills Book.author when asked for
}
@Module(controllers = [LibraryResolver::class]) class LibraryModule3. Switch it on:
app.http(NettyHttpAdapter(8080)) { useGraphQL { schema = SCHEMA } }4. Ask. Open http://localhost:8080/graphql in a browser for a small explorer, or send a query:
curl -X POST localhost:8080/graphql -H 'content-type: application/json' \
-d '{"query": "{ book(id: \"1\") { title author { name } } }"}'{ "data": { "book": { "title": "Dune", "author": { "name": "Frank Herbert" } } } }Ask for less and you get less: { books { title } } returns only titles, and author is never even loaded (the author resolver only runs when the query selects it). That is the point of GraphQL, and why @ResolveField exists.
How a request is answered
Variables
Never paste values into the query text. Send them separately, so the query stays the same and is safe:
{ "query": "query($id: ID!) { book(id: $id) { title } }", "variables": { "id": "1" }, "operationName": null }You can also GET /graphql?query=.... A browser GET without a query shows the explorer (explorer = false turns it off in production).
What to read next
- Resolvers: arguments, security, errors.
- Mutations and Subscriptions.
- Data loaders: avoid the "N+1" trap.
- Generating SDL: skip writing the schema by hand (code-first).
- Complexity: protect a public API.
Tested
Queries, mutations, subscriptions over WebSocket, variables, errors, guards, data loaders and the limits are exercised by automated tests against a running server.