Routzie - documentation

How to Use GraphQL

GraphQL is a powerful query language for APIs and a runtime for executing those queries. Below is a simple example of how to set up a GraphQL endpoint and handle requests in your application.

Example: Setting Up a GraphQL Endpoint

import { route, RouteResult, ProcessedRequest } from 'router'; import { graphql, buildSchema, GraphQLError } from 'graphql'; // Define your GraphQL schema const schema = buildSchema(` type Query { hello: String } `); // Define resolvers for your schema const rootValue = { hello: () => 'Hello world!' }; // Example with Fastify (or similar server) const app = Fastify(); app.post('/graphql', async (req, reply) => { const { query, variables } = req.body as { query: string, variables?: any }; const result = await graphql({ schema, source: query, variableValues: variables, rootValue, }); reply.send(result); }); app.listen({ port: 3000 }); // Example with custom route handler route(['GET', 'POST'], 'endpoint', async function(req: ProcessedRequest) { const { query, variables } = req.body as { query: string, variables?: any }; try { const result = await graphql({ schema, source: query, variableValues: variables, rootValue, }); return new RouteResult(result, 200); } catch (e) { if (e instanceof GraphQLError) { return new RouteResult({ error: e.message }, 400); } throw e; } });

How It Works

  1. Schema Definition: You define your GraphQL schema using buildSchema. This describes the types and queries your API supports.
  2. Resolvers: You provide resolver functions (like hello) that return data for each field in your schema.
  3. Handling Requests: When a request comes in, you pass the query and variables to the graphql function, which executes the query against your schema and resolvers.
  4. Error Handling: If a GraphQL error occurs, you can catch it and return a suitable error response.

This setup allows you to easily add a flexible GraphQL API to your application, supporting both GET and POST requests.

© 2025 Routzie Routzie.com