advanced#Node.js#GraphQL
Using Node.js with GraphQL
Learn how to use Node.js with GraphQL to create a simple API.
Introduction to GraphQL
GraphQL is a query language for APIs that allows clients to specify exactly what data they need.
Step 1: Install GraphQL
Install GraphQL using npm.
npm install graphql
Step 2: Create a New GraphQL Schema
Create a new GraphQL schema.
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: () => ({
hello: {
type: GraphQLString,
resolve: () => 'Hello World!'
}
})
})
});
Step 3: Create a GraphQL Server
Create a GraphQL server using Express.
const express = require('express');
const app = express();
const { graphqlHTTP } = require('express-graphql');
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true
}));
Step 4: Run the Server
Run the server.
node server.js
Open a web browser and navigate to http://localhost:3000/graphql to see the GraphQL API in action.