Express integration helps you connect GraphQL with a web server so you can handle requests easily.
Express integration in GraphQL
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const app = express(); const schema = buildSchema(` type Query { hello: String } `); const root = { hello: () => 'Hello world!' }; app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true })); app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
Use express-graphql middleware to connect GraphQL with Express.
Enable graphiql: true to get a web interface for testing queries.
app.use('/graphql', graphqlHTTP({ schema, rootValue, graphiql: true }));
app.use('/api', graphqlHTTP({ schema, rootValue, graphiql: false }));
app.use('/graphql', graphqlHTTP(req => ({ schema, rootValue, context: { user: req.user }, graphiql: true })));
This program creates a GraphQL server with Express. It defines a query greet that takes a name and returns a greeting. You can test it by visiting the GraphiQL interface.
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql'); const app = express(); const schema = buildSchema(` type Query { greet(name: String!): String } `); const root = { greet: ({ name }) => `Hello, ${name}!` }; app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true })); app.listen(4000, () => console.log('Server running on http://localhost:4000/graphql'));
Remember to install express, graphql, and express-graphql packages before running.
GraphiQL is a helpful tool for beginners to try queries in the browser.
Express integration lets you add other middleware like logging or authentication easily.
Express integration connects GraphQL to a web server for easy HTTP handling.
Use express-graphql middleware with a schema and root resolver.
Enable GraphiQL for a friendly query interface during development.
Practice
express-graphql middleware in an Express app?Solution
Step 1: Understand the role of middleware in Express
Middleware functions in Express handle requests and responses, adding features to the server.Step 2: Identify what
This middleware connects a GraphQL schema and resolvers to Express, enabling GraphQL queries over HTTP.express-graphqldoesFinal Answer:
To connect a GraphQL schema to the Express server for handling HTTP requests -> Option BQuick Check:
express-graphql middleware = Connect GraphQL to Express [OK]
- Thinking it creates a database connection
- Confusing it with static file serving
- Assuming it replaces Express entirely
express-graphql middleware in an Express app?Solution
Step 1: Recall the correct syntax for express-graphql middleware
The middleware is used withapp.useand takes an options object with keys likeschema,rootValue, andgraphiql.Step 2: Check each option for correct usage
app.use('/graphql', graphqlHTTP({ schema: mySchema, rootValue: rootResolver, graphiql: true })); correctly usesapp.usewith an options object includingschema,rootValue, andgraphiql. Others either misuse method or pass wrong arguments.Final Answer:
app.use('/graphql', graphqlHTTP({ schema: mySchema, rootValue: rootResolver, graphiql: true })); -> Option DQuick Check:
express-graphql needs options object with schema and rootValue [OK]
- Using app.get or app.post instead of app.use
- Passing schema and rootValue as separate arguments
- Omitting the graphiql option during development
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = {
hello: () => 'Hello world!'
};
const app = express();
app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: false }));
app.listen(4000);What will be the JSON response to this POST query to
/graphql?{"query": "{ hello }"}Solution
Step 1: Understand the schema and resolver
The schema defines a Query type with a fieldhelloreturning a String. The root resolver returns 'Hello world!' forhello.Step 2: Analyze the query and response
The query requests{ hello }. The resolver returns 'Hello world!', so the response JSON includes this underdata.Final Answer:
{"data":{"hello":"Hello world!"}} -> Option AQuick Check:
Query hello returns 'Hello world!' [OK]
- Expecting an error when schema and resolver match
- Confusing null with missing data
- Assuming graphiql affects response format
app.use('/graphql', graphqlHTTP({
schema: mySchema,
rootValue: rootResolver
}));But when you send queries, you get an error:
Cannot POST /graphql. What is the likely cause?Solution
Step 1: Understand the error message
The error 'Cannot POST /graphql' means Express does not recognize POST requests to that route.Step 2: Check middleware setup for POST data
GraphQL POST requests send JSON body. Express needs body parser middleware (likeexpress.json()) to parse JSON bodies before graphqlHTTP.Final Answer:
You did not enable the body parser middleware for JSON -> Option AQuick Check:
Missing JSON body parser causes POST errors [OK]
- Assuming graphqlHTTP handles JSON parsing automatically
- Confusing app.use with app.get
- Blaming schema definition for routing errors
user(id: ID!): User to your GraphQL schema in Express. The User type has fields id and name. Which of the following shows the correct way to extend the schema and resolver for this, assuming you have a getUserById function?Solution
Step 1: Define schema with required argument and User type
The schema must declareuser(id: ID!): Userto require an ID argument and return a User object.Step 2: Write resolver matching argument destructuring
The resolver function receives an object with arguments, so destructure{id}and pass it togetUserById.Final Answer:
Schema: type Query { user(id: ID!): User } and resolver: { user: ({id}) => getUserById(id) } -> Option CQuick Check:
Schema arg ID! and resolver destructure args [OK]
- Not marking ID as non-null with !
- Passing args incorrectly in resolver
- Using wrong argument type in schema
Ready to prove it?
Pass the test and this pattern moves unknown
