- Backend Weekly
- Posts
- API and API Design: How GraphQL APIs Work?
API and API Design: How GraphQL APIs Work?
We will discuss one API style called GraphQL, we will look at how GraphQL works and the different components of GraphQL.
Hello “👋
Welcome to another week, another opportunity to become a Great Backend Engineer.
Today’s issue is brought to you by Masteringbackend → A great resource for backend engineers. We offer next-level backend engineering training and exclusive resources.
Before we get started, I have a few announcements:
I have a special gift for you: You will love this one.
Unlock Windsurf Editor, by Codeium.
Introducing the Windsurf Editor, the first agentic IDE. All the features you know and love from Codeium’s extensions plus new capabilities such as Cascade that act as collaborative AI agents, combining the best of copilot and agent systems. This flow state of working with AI creates a step-change in AI capability that results in truly magical moments.
Now, back to the business of today.
In my previous series, I explored everything you need to know and learn about API and API Designs: Different API Styles
Today, we will discuss one API style called GraphQL, we will look at how GraphQL works and the different components of GraphQL.
This comes from my Backend Engineering Hub under the API and API Design section. However, I’m only transferring the knowledge here and breaking it down in this series one topic at a time.
How Does GraphQL Work?
In modern APIs, GraphQL has emerged as a powerful alternative to REST, offering flexibility, efficiency, and precise data retrieval. Developed by Facebook in 2012 and open-sourced in 2015, GraphQL addresses many limitations of traditional API design.
The Basics of GraphQL
At its core, GraphQL is a query language and runtime for APIs. Unlike REST, which exposes multiple endpoints for different resources, GraphQL consolidates everything into a single endpoint.
Clients send queries to this endpoint, specifying exactly what data they need, and the server responds with precisely that data. This eliminates the issues of overfetching (retrieving unnecessary data) and underfetching (requiring multiple requests to gather all needed data).
For example, in a REST API, fetching a user’s details and their posts might require two endpoints:
/users/:id
/users/:id/posts
In GraphQL, this can be achieved with a single query:
query {
user(id: 1) {
name
email
posts {
title
content
}
}
}
The server processes this query and returns only the requested fields in a structured JSON format:
{
"data": {
"user": {
"name": "Jane Doe",
"email": "jane.doe@example.com",
"posts": [
{
"title": "GraphQL Basics",
"content": "Understanding how GraphQL works..."
},
{
"title": "Advanced GraphQL",
"content": "Diving deeper into GraphQL queries..."
}
]
}
}
}
The Anatomy of GraphQL
To understand how GraphQL works, it’s important to break it down into its key components:
Schema
Query
Resolvers
Mutations
Schema
The schema is the backbone of a GraphQL API. It defines the structure of the data available through the API, including the types of resources and their relationships. Think of it as a contract between the client and the server.
Example of a simple schema for a blog application:
type User {
id: ID!
name: String!
email: String!
posts: [Post]
}
type Post {
id: ID!
title: String!
content: String!
author: User
}
type Query {
user(id: ID!): User
posts: [Post]
}
The schema can be the same with your database table fields or any data you want to expose to the Frontend.
Query
Clients use GraphQL queries to request data. The query language is flexible and allows clients to specify exactly what fields they need.
Here’s an example of a Query:
query {
posts {
title
author {
name
}
}
}
This query is exactly what your Frontend engineer will send to the backend to retrieve data. From this query, it is clear that the Frontend is looking to retrieve a collection of posts with the title and the author's name.
The server returns only the requested fields:
{
"data": {
"posts": [
{
"title": "GraphQL Basics",
"author": {
"name": "Jane Doe"
}
},
{
"title": "Advanced GraphQL",
"author": {
"name": "John Smith"
}
}
]
}
}
Resolvers
Resolvers are functions on the server side that fetch the actual data for the fields requested in the query. They connect the GraphQL API to the data sources, such as databases or other APIs. This is where your backend logic happens.
Example resolver for a user
query:
const resolvers = {
Query: {
user: (parent, args, context) => {
return context.db.getUserById(args.id);
}
}
};
The resolver above resolves the query when the Frontend requests a user detail. It finds the user via the ID specified and returns it to the Frontend as a response.
Mutations
While queries fetch data, mutations modify it. Mutations allow clients to perform operations like creating, updating, or deleting data. Inside the resolver explained above, you can also define a Mutation object to resolve all the mutations that will be created in your backend.
Here’s an example for your backend:
const resolvers = {
Mutation: {
addPost: (parent, args, context) => {
return context.db.addPost(args.title, args.content);
}
}
};
Example mutation to add a new post:
mutation {
addPost(title: "New GraphQL Post", content: "GraphQL is amazing!") {
id
title
}
}
The server responds with the newly created post:
{
"data": {
"addPost": {
"id": "101",
"title": "New GraphQL Post"
}
}
}
Key Features and Benefits of GraphQL
Flexible Queries: Clients can request only the data they need, reducing overfetching and underfetching.
Single Endpoint: GraphQL APIs consolidate all resources into a single endpoint, simplifying client-side development.
Strong Typing: The schema provides a clear contract, ensuring clients and servers understand the data structure.
Real-Time Capabilities: With subscriptions, GraphQL can handle real-time updates, making it suitable for dynamic applications like chat apps or live dashboards.
Tooling and Ecosystem: GraphQL’s introspection capabilities enable powerful developer tools like GraphiQL and Apollo Client to test and interact with APIs.
Challenges of GraphQL
While GraphQL offers numerous advantages, it’s not without challenges:
Complexity in Implementation: Setting up resolvers and schema can be more complex than a REST API.
Overhead for Simple Use Cases: For straightforward APIs, GraphQL might be overkill.
Query Performance: Complex nested queries can lead to performance issues if not optimized.
GraphQL is revolutionizing the way APIs are designed and consumed, offering unparalleled flexibility and precision in data retrieval. Its ability to empower clients to shape their data needs makes it ideal for modern, dynamic applications. While it’s not a silver bullet, understanding how GraphQL works and when to use it can help developers build more efficient and scalable APIs.
Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.
See you on Next Week.
Remember to start learning backend engineering from our courses:
Top 5 Remote Backend Jobs this week
Here are the top 5 Backend Jobs you can apply to now.
👨‍💻 Flying Bisons
✍️ Backend Developer
đź“ŤRemote
đź’° Click on Apply for salary details
Click here to Apply for this role.
👨‍💻 Automattic Inc
✍️ Backend Software Engineer
đź“ŤRemote, Worldwide
đź’° Click on Apply for salary details
Click here to Apply for this role.
👨‍💻 homepage
✍️ Backend Developer PHP
đź“ŤRemote, Worldwide
đź’° Click on Apply for salary details
Click here to Apply for this role.
👨‍💻 Constructor
✍️ Backend Engineer: Search Features & APIs (Remote)
đź“ŤRemote
đź’° Click on Apply for salary details
Click here to Apply for this role.
Want more Remote Backend Jobs? Visit GetBackendJobs.com
Backend Engineering Resources
Whenever you're ready
There are 4 ways I can help you become a great backend engineer:
1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.
2. ​The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.
3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.
4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.
LAST WORD đź‘‹
How am I doing?
I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?
Hit reply and say hello - I'd love to hear from you!
Stay awesome,
Solomon
I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.
Reply