basic express graphql

  1. Install necessary dependencies: bash npm install express express-graphql graphql

  2. Import required modules in your Express application: javascript const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql');

  3. Define your GraphQL schema using the buildSchema function: javascript const schema = buildSchema(` type Query { hello: String } `);

  4. Implement resolver functions for the defined schema: javascript const root = { hello: () => 'Hello, GraphQL!' };

  5. Create an Express app instance: javascript const app = express();

  6. 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 }));

  7. 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`); });

  8. Run your Express application: bash node your_app_file.js

  9. Open your browser and navigate to http://localhost:3000/graphql to access the GraphiQL interface.

  10. Test your GraphQL query in the GraphiQL interface: graphql query { hello } Execute the query and observe the result.