What is GraphQL?
GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It provides a more flexible and efficient alternative to REST APIs by enabling clients to request only the data they need, making it ideal for modern applications.
Key Features of GraphQL:
1. Single Endpoint: Instead of multiple endpoints, GraphQL uses a single endpoint to handle all queries and mutations.
2. Client-Defined Queries: Clients can specify exactly what data they need, reducing over-fetching or under-fetching.
3. Strongly Typed Schema: GraphQL APIs are defined by a schema that describes the types of data and relationships between them.
4. Real-Time Data: Supports subscriptions for real-time updates.
Hereβs how to build a GraphQL API with Node.js and PostgreSQL:
1. Set Up Your Project:
- Initialize a Node.js project:
mkdir graphql-node-postgres
cd graphql-node-postgres
npm init -y
- Install dependencies:
npm install express graphql express-graphql pg prisma dotenv
2. Configure PostgreSQL
Create a PostgreSQL database.
Define your tables. Example SQL for a users table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE NOT NULL,
age INT
);
3. Set Up Prisma (Optional for ORM)
- Initialize Prisma:
npx prisma init
- Update the prisma/schema.prisma file to define your data model:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
age Int
}
- Migrate the schema to your database:
npx prisma migrate dev --name init
4. Build the GraphQL Schema
- Define the GraphQL schema using graphql package:
const { GraphQLObjectType, GraphQLSchema, GraphQLString, GraphQLInt, GraphQLList, GraphQLNonNull } = require('graphql');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLInt },
name: { type: GraphQLString },
email: { type: GraphQLString },
age: { type: GraphQLInt },
},
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
users: {
type: new GraphQLList(UserType),
resolve: async () => await prisma.user.findMany(),
},
user: {
type: UserType,
args: { id: { type: GraphQLInt } },
resolve: async (_, args) => await prisma.user.findUnique({ where: { id: args.id } }),
},
},
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
createUser: {
type: UserType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
email: { type: new GraphQLNonNull(GraphQLString) },
age: { type: GraphQLInt },
},
resolve: async (_, args) => {
return await prisma.user.create({
data: {
name: args.name,
email: args.email,
age: args.age,
},
});
},
},
},
});
const schema = new GraphQLSchema({
query: RootQuery,
mutation: Mutation,
});
module.exports = schema;
5. Set Up Express and GraphQL Middleware
- Create an index.js file to run the server:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const schema = require('./schema');
require('dotenv').config();
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true, // Enable GraphiQL for testing
}));
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}/graphql`);
});
6. Run the Server
- Start the server:
node index.js
- Open http://localhost:4000/graphql to test your GraphQL API.
Example GraphQL Queries
- Fetch all users:
query {
users {
id
name
email
age
}
}
- Fetch a user by ID:
query {
user(id: 1) {
name
email
}
}
- Create a new user:
mutation {
createUser(name: "John Doe", email: "john@example.com", age: 30) {
id
name
email
}
}
I hope you found it helpful. Thanks for reading. π
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)