Create GraphQL API With Example

Read it in 15 Mins

Last updated on
01st Feb, 2022
Published
05th Jan, 2022
Views
5,004
Create GraphQL API With Example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!

What is GraphQL? A quick primer

Before understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.

Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.

Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.

But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.

  • GraphQL is Client-Driven, whereas REST is Server-Driven.
  • Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.
  • GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.
  • Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.

Some of the other advantages of using GraphQL are:

  • GraphQL is faster than other communication APIs.
  • GraphQL can retreat multiple resources and results with a single request.
  • It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.
  • It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.
  • No under and over data fetching. It fetches the amount of data that is required.

The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.

The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.

GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.

Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.

Let’s Play with GraphQL

To get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.

Prerequisites:

  • Understanding of GraphQL
  • Node Package Manager (or NPM) with version 10+
  • Knowledge of basic querying and server-side programming.

We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.

So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.

Setting up Express GraphQL

Let’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.

$ mkdir graphql-example 
$ cd graphql-example

Use NPM to intiialize a project

$ npm init -y

Install the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.

$ npm install express mongoose body-parser cors --save

Apollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.

$ npm install apollo-server-express --save

This should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.

This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.

const express = require('express'); 
const mongoose = require('mongoose'); 
const schema = require('./schema'); 
const bodyParser = require('body-parser'); 
const cors = require('cors'); 
const { ApolloServer } = require('apollo-server-express'); 

const url = "mongodb://localhost:27017/moviesdb"; 
const connect = mongoose.connect(url, { useNewUrlParser: true }); 
connect.then((db) => { 
      console.log('Connected correctly to server!'); 
}, (err) => { 
      console.log(err); 
}); 

const server = new ApolloServer({ 
      typeDefs: schema.typeDefs, 
      resolvers: schema.resolvers 
}); 

const app = express(); 
app.use(bodyParser.json()); 
app.use('*', cors()); 
server.applyMiddleware({ app }); 
app.listen({ port: 4000 }, () => 
  console.log(`Server ready at 
http://localhost:4000${server.graphqlPath}`));

In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.

In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.

In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.

In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.

GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.

Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.

const mongoose = require('mongoose'); 

const Schema = mongoose.Schema; 
const movieSchema = new Schema({ 
    name: { 
       type: String, 
       required: true 
    }, 
    rating: { 
       type: Number, 
       required: true 
    }, 
    producer: { 
       type: String, 
       required: true 
   } 
}, { 
    timestamps: true 
}); 

var Movies = mongoose.model('Movie', movieSchema); 
module.exports = {Movies, movieSchema};

We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.

In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.

Designing the Schema

Let’s move on to the schema.js file where you’re going to build our GraphQL API.

Create a new file in the root of the folder by the name of schema.js and add the following code.

const { gql } = require('apollo-server-express'); 
  const Movie = require('./models/movie').Movies; 

  const typeDefs = gql ` 
   type Movie { 
     id: ID! 
     name: String! 
     producer: String! 
     rating: Float! 
 } 
 type Query { 
   getMovies: [Movie] 
   getMovie(id: ID!): Movie 
 } 
 type Mutation { 
     addMovie(name: String!, producer: String!, rating: Float!): Movie 
     updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie 
     deleteMovie(id: ID!): Movie 
   } 
`

In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.

Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.

Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:

const resolvers = { 
  Query: { 
    getMovies: (parent, args) => { 
      return Movie.find({}); 
    }, 

    getMovie: (parent, args) => { 
      return Movie.findById(args.id); 
    } 
  }, 
  Mutation: { 
    addMovie: (parent, args) => { 
      let movie = new Movie({ 
        name: args.name, 
        producer: args.producer, 
        rating: args.rating, 
      }); 
      return movie.save(); 
    }, 
    updateMovie: (parent, args) => { 
      if (!args.id) return; 
        return Movie.findOneAndUpdate( 
         { 
           _id: args.id 
         }, 
         { 
           $set: { 
             name: args.name, 
             producer: args.producer, 
             rating: args.rating, 
           } 
         }, {new: true}, (err, Movie) => { 
           if (err) { 
             console.log('Something went wrong when updating the movie'); 
           } else { 
             continue; 
           } 
         } 
      ); 
    } 
  } 
} 

module.exports = {typeDefs,resolvers};

This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.

With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.

$ node index.js 
Server ready at http://localhost:4000/graphql

Once the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.

mutation {
addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) {
id,
name,
rating,
producer
}
}

OUTPUT:

{
“data” : {
“addMovie”: {
“id”: “5j2j1lnk1LNS231MLK3”,
“name”: “GraphQL Movie”,
“producer”: “Facebook”,
“rating”: 4.5
}
}
}

And now let’s list out all the movies in the database with only their “name” and “rating”.

query {
getMovies: {
name,
rating
}
}

OUTPUT:

{
“Data”: {
“getMovies”: [
{
“name”: “GraphQL Movie”,
“rating”: 4.5
}
]
}
}

So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.

Using GraphQL with React

Using GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.

Start off by installing the required dependencies.

$ npm install create-react-app graphql @apollo/client

Create a new React app

npx create-react-app movies-app

Let’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:

import { 
  ApolloClient, 
  InMemoryCache, 
  ApolloProvider, 
  useQuery, 
  gql 
} from "@apollo/client"; 

const client = new ApolloClient({ 
  uri: 'https://48p1r2roz4.sse.codesandbox.io', 
  cache: new InMemoryCache() 
});

The URI specifies the GraphQL Server URL.

That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.

function App() {
  return (
    <div>
      <h2>My first GraphQL app </h2>
    </div>
  );
}

render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root'),
);

With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.

In the index.js, let’s first define the query you want to execute.

const MOVIES = gql`
  query getMovies {
     name,
     producer
  }
`;

Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:

function GetMovies() {

  const { loading, error, data } = useQuery(MOVIES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.map(({ name, producer }) => (
    <div key={name}>
      <p>
        {name}: Produced by {producer}
      </p>
    </div>
  ));
}

Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.

Finally, you'll add GetMovies to our existing component tree:

function App() {
  return (
    <div>
      <h2>My first Apollo app </h2>

      <GetMovies />
    </div>
  );
}

When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.

Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.

Dev-friendly Query Languages are the Future

So, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.

We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.

Keep Learning.

Profile

Amit Tomar

Author

I'm a final year engineering student who is fascinated with technical world. I'm an AWS certified solution architect and being a community person I've been a part of multiple communities including Microsoft Student Ambassador, Google Developer Student Club and AWS community builder.