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:
- You get the information exactly in the amount in which you request. Unlike REST, the response to the request will not contain unnecessary data.
- You will need only one endpoint, no additional versions for a single API.
- 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.json
in 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.json
and 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.
src
Create 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: "john@gmail.com", age: 22 }, { id: 2, name: "Jane Doe", email: "jane@gmail.com", 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 src
should look like this:
src |--db.js |--resolvers.js |--schema.graphql
Now you need to run the command npm run dev
for npm or yarn dev
for yarn. The terminal should display information about the successful launch of the server:
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
, email
and 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.graphql
and replace the previously specified Query type with the following code:
type User { id: ID! name: String! email: String! age: Int }
Each type record User
must have an identification number, therefore the field id
contains 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:
- queries , queries – with their help they receive data from the server.
- mutations , changes – modification of data on the server and their updating.
- subscriptions , subscriptions – methods of maintaining constant communication with the server.
Requests
GraphQL Requests
Open the file schema.graphql
and add the type Query
:
type Query { users: [User!]! }
The query users
will 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, User
you must create a corresponding request. In this case, it will be a query user
in 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 hello
with 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 id
database entry field as an argument . The server returns the contents of a suitable record. The query users
contains 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.graphql
and 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 fieldsid
,name
,email
andage
. The function returns a type recordUser
.updateUser
: you must pass a field valueid
, a new field valuename
,email
orage
. The function returns a type recordUser
.deleteUser
: it is necessary to transfer field valueid
. The function returns a type recordUser
.
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: "robert@gmail.com", 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.