Simple GraphQL API with Node and Express

ยท

2 min read

Simple GraphQL API with Node and Express

Sure, creating a GraphQL API involves setting up a server with Node.js, Express, and a GraphQL library (such as Apollo Server). Below is a step-by-step guide to creating a simple GraphQL API.

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir graphql-api
     cd graphql-api
    
  2. Initialize a new Node.js project:

     npm init -y
    
  3. Install necessary dependencies:

     npm install express apollo-server-express graphql
    

Step 2: Create Your Folder Structure

Create the following folder structure:

graphql-api/
|-- src/
|   |-- schema/
|       |-- schema.js
|   |-- resolvers/
|       |-- queries.js
|   |-- app.js
|-- server.js

Step 3: Set Up Apollo Server with Express

In app.js, set up Apollo Server with Express:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./schema/schema');
const resolvers = require('./resolvers/queries');

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();

server.applyMiddleware({ app });

module.exports = app;

Step 4: Define GraphQL Schema

In schema/schema.js, define your GraphQL schema:

const { gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

module.exports = typeDefs;

Step 5: Implement Resolvers

In resolvers/queries.js, implement resolvers for your GraphQL queries:

const resolvers = {
  Query: {
    hello: () => 'Hello, GraphQL!',
  },
};

module.exports = resolvers;

Step 6: Set Up Express Server

In server.js, set up the Express server:

const app = require('./src/app');

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}/graphql`);
});

Step 7: Run Your Application

Start the server:

node server.js

Visit http://localhost:3000/graphql in your browser or use a tool like GraphQL Playground to explore your GraphQL API.

Step 8: Test Your GraphQL API

Write a simple GraphQL query in GraphQL Playground or any GraphQL client:

query {
  hello
}

You should receive the response:

{
  "data": {
    "hello": "Hello, GraphQL!"
  }
}

Congratulations! You've set up a basic GraphQL API with Node.js, Express, and Apollo Server. From here, you can expand your schema, add mutations, integrate with a database, and create more complex GraphQL APIs based on your application's requirements.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย