GraphQL API Beginner’s Guide

GraphQL API Beginner’s Guide

API stands for Application Programming Interface (application programming interface). This, as the name implies, is the interface through which the parties to the exchange interact.

In this article, you will learn the basics of API development using the GraphQL standard.

What is GraphQL

GraphQL is an open source query language developed by Facebook. It was created as a more efficient alternative to REST for developing and using application programming interfaces.

GraphQL has many advantages, for example:

  1. You get the information exactly in the amount in which you request. Unlike REST, the response to the request will not contain unnecessary data.
  2. You will need only one endpoint, no additional versions for a single API.
  3. GraphQL is a strongly typed language that allows you to pre-evaluate the correctness of a query within the framework of the type system of this syntax, prior to execution. This allows you to develop more powerful APIs.

Where to begin

In order to understand how to apply the standard in practice, we will use the server in the basic configuration – Graphpack.

First you need to create a new folder for the project. In this case, the folder name will be graphql-server, but the name is not important.

Open a terminal and enter:

mkdir graphql-server

You must have npm or yarn installed on your computer .

Go to the folder you created if you have not done it yet and enter the command depending on the manager you are using:

npm init -y

or

yarn init

npm will create a file package.jsonin which all dependencies and commands you create will be stored.

Now you need to install one dependency, which we will use in this article.

Graphpack allows you to create a GraphQL server with a basic configuration. This feature will allow you to continue working without wasting time on setup.

Using the terminal, install Graphpack in the root folder of the project using the following command:

npm install --save-dev graphpack

Or if you use yarn:

yarn add --dev graphpack

After installing Graphpack, go to the file package.jsonand add the following code:

"scripts": { "dev": "graphpack", "build": "graphpack build" }

Create a folder on the server src. In this example, this will be the only folder on the server in which you will need to create three files.

srcCreate a file in the folder schema.graphql. Add code to this file:

type Query { hello: String }

This file will contain the entire GraphQL schema.

Create a second file in the same folder, name it resolvers.js. Put the following code there:

import { users } from "./db";

const resolvers = { Query: { hello: () => "Hello World!" } };

export default resolvers;

This file will contain instructions for performing GraphQL operations.

Create a third file db.js, containing the code:

export let users = [ { id: 1, name: "John Doe", email: "", age: 22 }, { id: 2, name: "Jane Doe", email: "", age: 23 } ];

For learning to work with GraphQL there is no need to use real data. This file is needed to simulate database access.

After performing the operations, the folder srcshould look like this:

src |--db.js |--resolvers.js |--schema.graphql

Now you need to run the command npm run devfor npm or yarn devfor yarn. The terminal should display information about the successful launch of the server:

GraphQL server started

GraphQL server started

Now you can go to localhost:4000. The system is ready to work on an API based on GraphQL. IDE GraphQL Playground is used for development.

Scheme

GraphQL uses its own Schema Definition Language (SDL) to create schemas. SDL has an intuitive syntax and is universal for any technology used.

Types

Types is one of the main features of GraphQL. These are custom objects that define what the API will look like. For example, when developing an application programming interface for interacting with social networks, it is necessary to declare types in the API Posts, Users, Likes, Groups.

Types have fields that return certain types of data. For example, when you create the User type, should include fields in it name, emailand age. Type fields can be any and always return data in Int, Float, String, Boolean, ID, List of Object Types, or Custom Objects Types formats.

To create the first type, open the file schema.graphqland replace the previously specified Query type with the following code:

type User { id: ID! name: String! email: String! age: Int }

Each type record Usermust have an identification number, therefore the field idcontains data of the corresponding type. Fields name and email contain a String (variable of type of a string of characters), and age – an integer variable.

An exclamation point at the end of a field definition means that this field cannot be empty. The only field without an exclamation mark is age.

GraphQL operates with three main concepts:

  1. queries , queries – with their help they receive data from the server.
  2. mutations , changes – modification of data on the server and their updating.
  3. subscriptions  , subscriptions – methods of maintaining constant communication with the server.

Requests

GraphQL Requests

GraphQL Requests

Open the file schema.graphqland add the type Query:

type Query { users: [User!]! }

The query userswill return an array of one or more type records User. Since the definition uses exclamation marks, the response to the request cannot be empty.

To obtain a specific record, Useryou must create a corresponding request. In this case, it will be a query userin the type Query. Add the following line to the code:

user(id: ID!): User!

Now the code should look like this:

type Query { users: [User!]! user(id: ID!): User! }

As you can see, in GraphQL queries, you can pass arguments. In this case, to get a specific record in the request, its field is used as an argument id.

The location of the data that will be processed in accordance with the request is defined in the file resolvers.js. Open this file and import the training database db.js:

import { users } from "./db";

const resolvers = { Query: { hello: () => "Hello World!" } };

export default resolvers;

Then replace the function hellowith user and users:

import { users } from "./db";

const resolvers = { Query: { user: (parent, { id }, context, info) => { return users.find(user => user.id === id); }, users: (parent, args, context, info) => { return users; } } };

export default resolvers;

Each query resolver has four arguments. The query user passes the contents of the iddatabase entry field as an argument . The server returns the contents of a suitable record. The query userscontains no arguments and always returns the entire array.

To test the resulting code, go to localhost:4000.

The following code should return a list of all entries db.js:

query { users { id name email age } }

You can get the first record from the database using this code:

query { user(id: 1) { id name email age } }

Changes

In GraphQL, changes are a way to modify data on a server and get processed information. This process can be considered as similar to the CUD (Create, Update, Delete) concept in the REST standard.

To create a change, open the file schema.graphqland add a new type mutation:

type Mutation { createUser(id: ID!, name: String!, email: String!, age: Int): User! updateUser(id: ID!, name: String, email: String, age: Int): User! deleteUser(id: ID!): User! }

In this case, there are three different changes:

  • createUser: It is necessary to convey the value of fields id, name, emailand age. The function returns a type record User.
  • updateUser: you must pass a field value id, a new field value name, emailor age. The function returns a type record User.
  • deleteUser: it is necessary to transfer field value id. The function returns a type record User.

Now open the file resolvers.js and Query create a new object below the object mutation:

Mutation: { createUser: (parent, { id, name, email, age }, context, info) => { const newUser = { id, name, email, age };

  users.push(newUser);

  return newUser;
},
updateUser: (parent, { id, name, email, age }, context, info) => {
  let newUser = users.find(user => user.id === id);

  newUser.name = name;
  newUser.email = email;
  newUser.age = age;

  return newUser;
},
deleteUser: (parent, { id }, context, info) => {
  const userIndex = users.findIndex(user => user.id === id);

  if (userIndex === -1) throw new Error("User not found.");

  const deletedUsers = users.splice(userIndex, 1);

  return deletedUsers\[0\];
}

}

The full code of the file resolvers.js should look like this:

import { users } from "./db";

const resolvers = { Query: { user: (parent, { id }, context, info) => { return users.find(user => user.id === id); }, users: (parent, args, context, info) => { return users; } }, Mutation: { createUser: (parent, { id, name, email, age }, context, info) => { const newUser = { id, name, email, age };

  users.push(newUser);

  return newUser;
},
updateUser: (parent, { id, name, email, age }, context, info) => {
  let newUser = users.find(user => user.id === id);

  newUser.name = name;
  newUser.email = email;
  newUser.age = age;

  return newUser;
},
deleteUser: (parent, { id }, context, info) => {
  const userIndex = users.findIndex(user => user.id === id);

  if (userIndex === -1) throw new Error("User not found.");

  const deletedUsers = users.splice(userIndex, 1);

  return deletedUsers\[0\];
}

} };

export default resolvers;

Request to localhost:4000:

mutation { createUser(id: 3, name: "Robert", email: "", age: 21) { id name email age } }

It must return a new type entry User. Also try out the other functions of the change.

Subscriptions

As mentioned earlier, subscriptions maintain constant communication between clients and the server. The basic subscription is as follows:

subscription { users { id name email age } }

Although this code looks similar to the request, it works a little differently. When data is updated, the server executes the GraphQL query defined in the subscription and sends the updated data to the clients.

Conclusion

The GarphQL standard is gaining popularity. As part of the State of JavaScript survey conducted among JS developers, more than half of the respondents indicated that they had heard about this technology and would like to familiarize themselves with it, and one-fifth already use it and do not intend to refuse. If you believe this trend, GraphQL expects active development. We hope that this material has given you a general idea of ​​GraphQL and interested in further studying it.

The post GraphQL API Beginner’s Guide appeared first on Creador.

Did you find this article valuable?

Support Pawan Kumar by becoming a sponsor. Any amount is appreciated!