This is a basic example to get you started.
1. Setup Project:
Start by creating a new directory for your project and initializing a new Node.js project.
mkdir graphql-practical cd graphql-practical npm init -y
2. Install Dependencies:
Install the necessary dependencies using npm.
npm install express express-graphql graphql
3. Create Server:
Create a file named `server.js` and set up a basic Express server with GraphQL.
const express = require('express'); const { graphqlHTTP } = require('express-graphql'); const { buildSchema } = require('graphql');
// Define your GraphQL schema const schema = buildSchema(` type Query { hello: String } `);
// Define resolvers const root = { hello: () => 'Hello, GraphQL!' };
// Create an Express app const app = express();
// Create a route for handling GraphQL requests app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true // Enable GraphiQL for easy testing }));
// Start the server const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running at http://localhost:${PORT}/graphql`); });
4. Run the Server:
Execute the following command to run your server.
node server.js
Your GraphQL server should be running at http://localhost:3000/graphql.
5. Test with GraphQL:
Open your browser and navigate to http://localhost:3000/graphql. You should see the GraphiQL interface.
Try running the following query:
{ hello }
You should get the response `“Hello, GraphQL!”`.