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.
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; } });
buildSchema. This describes the types and queries your API supports.hello) that return data for each field in your schema.graphql function, which executes the query against your schema and resolvers.This setup allows you to easily add a flexible GraphQL API to your application, supporting both GET and POST requests.
© 2025 Routzie Routzie.com