basic express graphql
Install necessary dependencies:
bash npm install express express-graphql graphql
Import required modules in your Express application:
javascript const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql');
Define your GraphQL schema using the
buildSchema
function:javascript const schema = buildSchema(` type Query { hello: String } `);
Implement resolver functions for the defined schema:
javascript const root = { hello: () => 'Hello, GraphQL!' };
Create an Express app instance:
javascript const app = express();
Add a route for GraphQL using the
graphqlHTTP
middleware:javascript app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true // Enables the GraphiQL interface for testing }));
Set up the server to listen on a specific port (e.g., 3000):
javascript const port = 3000; app.listen(port, () => { console.log(`Express GraphQL server is running at http://localhost:${port}/graphql`); });
Run your Express application:
bash node your_app_file.js
Open your browser and navigate to http://localhost:3000/graphql to access the GraphiQL interface.
Test your GraphQL query in the GraphiQL interface:
graphql query { hello }
Execute the query and observe the result.