Unlock the Power of GraphQL: A Comprehensive Guide to Building a Scalable API
What is GraphQL?
GraphQL is a revolutionary data query language that offers a flexible approach to querying APIs. Unlike traditional REST APIs, GraphQL provides a single endpoint for performing CRUD (Create, Read, Update, Delete) operations on a data store. This flexibility allows frontend developers to request only the necessary data, reducing the amount of data transferred and improving application performance.
Setting Up a GraphQL API in Node.js
To get started, you’ll need to install Node.js on your computer if you haven’t already. Create a new project folder and navigate into it. Then, create a server subfolder and initialize a new Node project using the following terminal commands:
mkdir graphql-apollo
cd graphql-apollo
mkdir server
cd server
npm init -y
Next, install the required packages using the following command:
npm install graphql apollo-server-express express
Defining Your Schema
In GraphQL, a schema defines the structure and data types of your database. Create a new folder named Schemas
inside your server
folder, and then create a new file called User.js
inside the Types
folder. This file will define the type definition for a user entity:
“`javascript
import { GraphQLObjectType, GraphQLInt, GraphQLString } from ‘graphql’;
const UserType = new GraphQLObjectType({
name: ‘User’,
fields: {
id: { type: GraphQLInt },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString },
gender: { type: GraphQLString },
address: { type: GraphQLString },
},
});
export default UserType;
“`
Creating Queries and Mutations
Next, create an index.js
file in the Schemas
folder to define your queries and mutations. Start by importing the necessary types and fake user data:
“`javascript
import { GraphQLSchema, GraphQLObjectType, GraphQLList } from ‘graphql’;
import userData from ‘./users.json’;
import UserType from ‘./Types/User’;
const RootQuery = new GraphQLObjectType({
name: ‘RootQuery’,
fields: {
getAllUsers: {
type: new GraphQLList(UserType),
resolve: () => userData,
},
},
});
const CreateUserMutation = new GraphQLObjectType({
name: ‘CreateUserMutation’,
fields: {
createUser: {
type: UserType,
args: {
id: { type: GraphQLInt },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString },
gender: { type: GraphQLString },
address: { type: GraphQLString },
},
resolve: (parent, args) => {
const newUser = {…args };
userData.push(newUser);
return newUser;
},
},
},
});
const schema = new GraphQLSchema({
query: RootQuery,
mutation: CreateUserMutation,
});
export default schema;
“`
Starting the GraphQL Server
To start your GraphQL server, create an index.js
file in the root of your project and add the following code:
“`javascript
import express from ‘express’;
import { graphqlHTTP } from ‘express-graphql’;
import schema from ‘./Schemas’;
const app = express();
app.use(‘/graphql’, graphqlHTTP({
schema,
graphiql: true,
}));
app.listen(6969, () => {
console.log(‘GraphQL server listening on port 6969’);
});
“`
Testing Your API with GraphiQL
GraphiQL is a built-in GraphQL API testing environment that allows you to visualize your API calls. To access GraphiQL, navigate to http://localhost:6969/graphql
in your browser. You can write and execute test queries in the left window, and the results will appear in the right window.
Connecting to a React App using Apollo Client
To connect your GraphQL backend to a React frontend, you’ll need to install Apollo Client and GraphQL using the following command:
npm install @apollo/client graphql
Create a new file called ApolloClient.js
in your React app’s root folder and add the following code:
“`javascript
import { ApolloClient, InMemoryCache } from ‘@apollo/client’;
const client = new ApolloClient({
uri: ‘http://localhost:6969/graphql’,
cache: new InMemoryCache(),
});
export default client;
“`
Then, wrap your entire application inside the Apollo Provider:
“`javascript
import React from ‘eact’;
import ReactDOM from ‘eact-dom’;
import App from ‘./App’;
import ApolloClient from ‘./ApolloClient’;
ReactDOM.render(
document.getElementById(‘root’)
);
“`
Making Queries and Mutations with Apollo Client
Create a new file called Queries.js
in your React app’s root folder and define your queries and mutations:
“`javascript
import { gql } from ‘@apollo/client’;
const LOADUSERSQUERY = gql
;
query LoadUsers {
getAllUsers {
id
firstName
lastName
gender
address
}
}
const CREATEUSERMUTATION = gql
;
mutation CreateUser($id: Int!, $firstName: String!, $lastName: String!, $gender: String!, $address: String!) {
createUser(id: $id, firstName: $firstName, lastName: $lastName, gender: $gender, address: $address) {
id
firstName
lastName
gender
address
}
}
export { LOADUSERSQUERY, CREATEUSERMUTATION };
“`
Finally, use the useQuery
and useMutation
hooks to execute your queries and mutations in your React components:
“`javascript
import React, { useState, useEffect } from ‘eact’;
import { useQuery, useMutation } from ‘@apollo/client’;
import { LOADUSERSQUERY, CREATEUSERMUTATION } from ‘./Queries’;
const Users = () => {
const { data, error, loading } = useQuery(LOADUSERSQUERY);
if (loading) return
Loading…
;
if (error) return
Error: {error.message}
;
return (
-
{data.getAllUsers.map(user => (
-
))}
);
};
const Form = () => {
const [firstName, setFirstName] = useState(”);
const [lastName, setLastName] = useState(”);
const [gender, setGender] = useState(”);
const [address, setAddress] = useState(”);
const [createUser, { data, error }] = useMutation(CREATEUSERMUTATION);
const handleSubmit = async event => {
event.preventDefault();
await createUser({ variables: { firstName, lastName, gender, address } });
};
return (
);
};
“`
That’s it! You now have a fully functional GraphQL API with a React frontend using Apollo Client.