GraphQL: Introduction
we will explore the basics of GraphQL and learn how to connect it with front-end frameworks like React and React Native using Apollo. This will help you to understand how to build modern, efficient apps with GraphQL, React, React Native, and Apollo.
What is GraphQL?
GraphQL is a query language for APIs. It was developed by Facebook as a solution to fetch data more efficiently.
Why GraphQL ?
Before GraphQL
- A REST API (Representational State Transfer Application Programming Interface) is a standardized way of allowing different software systems to communicate.
In REST APIs, each endpoint will return a specific payload of JSON data. Even if we only need certain fields, it will return everything on every request.
Retrieve a List of Products
- HTTP Method: GET
- Endpoint:
/api/products
- Description: Retrieves a list of all products.
Request:
GET /api/products/1
Response:
[
{
"id": 1,
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"description": "A high-performance laptop suitable for all your computing needs.",
"manufacturer": "TechCorp",
"stock": {
"quantity": 50,
"warehouseLocation": "Warehouse A"
},
"specifications": {
"processor": "Intel Core i7",
"ram": "16GB",
"storage": "512GB SSD",
"screenSize": "15.6 inches"
},
"images": [
"https://example.com/images/laptop1.jpg",
"https://example.com/images/laptop2.jpg"
],
"ratings": {
"average": 4.5,
"count": 120
},
"reviews": [
{
"userId": 101,
"rating": 5,
"comment": "Excellent laptop for work and play.",
"date": "2023-06-15"
},
{
"userId": 102,
"rating": 4,
"comment": "Great performance but a bit pricey.",
"date": "2023-06-20"
}
]
},
{
"id": 2,
"name": "Smartphone",
"price": 599.99,
"category": "Electronics",
"description": "A sleek and powerful smartphone with the latest features.",
"manufacturer": "PhoneInc",
"stock": {
"quantity": 200,
"warehouseLocation": "Warehouse B"
},
"specifications": {
"processor": "Snapdragon 888",
"ram
Also, the design of REST APIs may require an app to make a lot of unnecessary requests because some data may be from different endpoints.
This means, in order to retrieve data about a specific you need to make different HTTP requests.
As demand for faster and more efficient apps increase among its users, Facebook recognized these issues in REST APIs.
In 2012, it began developing GraphQL internally before releasing it to the public in 2015
How GraphQL Works ?
As mentioned; it is a query language, which means it fetches only the data you need using queries.
With GraphQL :
- Less endpoints to manage only
/graphql
- Flexible integration with database, a REST API, a cloud service, and a JSON file
A typical GraphQL operation goes like this:
- Data is requested from the GraphQL server via a query.
- A function is called on the GraphQL server to get data from the appropriate source.
- The GraphQL server returns a response to the client.
GraphQL comes with an IDE called GraphiQL that is helpful for developers to test the API.
GraphQL extension for Visual Studio code
Key Features of GraphQL
Declarative Data Fetching: Clients specify the shape and size of the data they need.Avoids over-fetching (retrieving more data than needed) and under-fetching (retrieving less data than needed).
Single Endpoint: Unlike REST, which requires multiple endpoints for different resources, GraphQL uses a single endpoint to access all data.
Strongly Typed Schema : The schema defines the types of data that can be queried and the relationships between them.
Real-time Data with Subscriptions: Clients can subscribe to changes in data and receive updates in real-time.
Basic Structure of a GraphQL Query
Here’s a simple GraphQL query to fetch products:
Fetching a Single Product by ID:
GraphQL Query:
query {
product(id: 1) {
id
name
price
category
description
}
}
JSON Request:
{
"query": "query { product(id: 1) { id name price category description } }"
}
Example Response:
{
"data": {
"product": {
"id": 1,
"name": "Laptop",
"price": 999.99,
"category": "Electronics",
"description": "A high-performance laptop suitable for all your computing needs."
}
}
}
Adding a New, Update or Product (Mutation):
GraphQL Mutation:
mutation {
addProduct(input: {
name: "Tablet",
price: 299.99,
category: "Electronics",
description: "A lightweight tablet with a long battery life."
}) {
id
name
price
category
description
}
}
JSON Request:
{
"query": "mutation { addProduct(input: { name: \"Tablet\", price: 299.99, category: \"Electronics\", description: \"A lightweight tablet with a long battery life.\" }) { id name price category description } }"
}
Example Response:
{
"data": {
"addProduct": {
"id": 3,
"name": "Tablet",
"price": 299.99,
"category": "Electronics",
"description": "A lightweight tablet with a long battery life."
}
}
}
Update JSON Request
{
"query": "mutation { updateProduct(id: 1, input: { name: \"Laptop\", price: 1099.99, category: \"Electronics\", description: \"An updated high-performance laptop with additional features.\" }) { id name price category description } }"
}
Example Response:
{
"data": {
"updateProduct": {
"id": 1,
"name": "Laptop",
"price": 1099.99,
"category": "Electronics",
"description": "An updated high-performance laptop with additional features."
}
}
}
How to Use GraphQL with JSON
Define the Schema: Create a schema that defines the types and fields available in your API.
Set Up the Server: Use a server library like Apollo Server or Express GraphQL to handle requests.
Send Queries/Mutations: Use tools like GraphiQL, Apollo Client, or HTTP clients (e.g., Postman, cURL) to send queries and mutations in JSON format
Process the Response: Handle the JSON response from the server, which includes the requested data or confirmation of mutation operations.
GraphQL’s ability to handle complex queries and return precise data in JSON format makes it a powerful alternative to traditional REST APIs, enabling more efficient and flexible data fetching.