Getting Started with GraphQL: Efficient Data Retrieval

Getting Started with GraphQL: Efficient Data Retrieval

A Quick Introduction to GraphQL for Modern API Requests

🤔 What is GraphQL?

GraphQL is a query language developed by Facebook that allows you to efficiently retrieve only the data you need from servers.

🗝️ Key Concepts

  • Schema: The plan that describes data types and how to use them.

  • Queries: Requests made to the server to get specific data.

  • Mutations: Used for changing data on the server, like updating a profile.

  • Resolvers: Functions that handle data based on queries and mutations.

Here's an example of how a query could look:

 query {
  getUser(id: "abc123") {
    id
    name
    email
  }
}

🌐 Comparing GraphQL and REST

Let's explore the differences between these two methods of working with APIs.

🥜 REST in a Nutshell

It's a traditional method to get data from a server.

You ask for data from specific endpoints, but this can give you too much data or make you ask for data many times to get what you want.

Pros:

  • Familiar and widely used.

  • Supports caching and browser history.

cons:

  • Overfetching and underfetching data.

  • Requires multiple requests for related data.

🦄 GraphQL: A Precise Approach

It's a modern alternative that lets you request exactly the data you want.

You send a query to a single endpoint, and the server responds with the specific data you asked for.

Pros:

  • Gets only the requested data.

  • One endpoint for all queries.

  • Ensures data consistency with a structured schema.

Cons:

  • May require some learning because it works differently from what you might be used to with REST.

🤷🏽‍♀️ Choosing the Right Fit

Consider GraphQL if you appreciate:

  • Getting exactly the data you need.

  • Fetching related data in one request.

  • Data that follows clear rules for consistency.

Choose REST if you prefer:

  • Something you're already familiar with and is simple.

  • Speeding things up using a cache (a way to store data for quicker access).

  • Keeping track of what you do in your web browser's history.

  • A straightforward approach for basic APIs (ways to connect with online services).

🌐 Core Concepts of GraphQL

Here are the key things to know about GraphQL:

Types:

  • String: text

  • Int: whole numbers

  • Float: decimal numbers

  • Boolean: true/false

  • ID: key for data object

📜 Schema Definition Language (SDL)

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

❗️ means Non-Nullable: any type followed by an exclamation mark means that the field must always have a value and that it cannot be nullable.

🗺️ Schema

A schema defines the capabilities of your API. It acts as a contract between the client and the server. In your schema:

type Query {
  getUser(id: ID!): User

}

type Mutation {
  updateUser(id: ID!, name: String!): User
}

The schema includes three root types: Query, Mutation, and Subscription.

  • Query allows clients to retrieve data.

  • Mutation is for modifying data, such as updating a user's name.

  • Subscription enables real-time updates.

📋 Queries

Queries are the way clients request data from your API. In your query:

query {
  getUser(id: "abc123") {
    name
    email
  }
}

Clients use queries to request specific data fields. In this example, we're requesting the name and email fields for a user.

🔄 Mutation

Mutations change data in your API. When you perform a mutation, like creating or updating something, GraphQL often responds with a payload.

Payload is like a message that tells you what happened.

For example, if you create a user, the payload might show the user's ID and name, confirming the action and what was changed. It's a way to notify you about what occurred.

Create Mutation:

mutation {
  createUser(name: "John", age: 30) {
    id
    name
  }
}

Update Mutation:

mutation {
  updateUser(id: "abc123", name: "New Name") {
    id
    name
  }
}

Delete Mutation:

mutation {
  deleteUser(id: "xyz789") {
    id
  }
}

📡 Subscription

Subscriptions in GraphQL make things happen in real time. They allow clients to join special events and get instant updates when these events occur. Subscriptions are super useful for chat apps, live notifications, and real-time dashboards.

🥳 Example of Full Schema

Here's an example of how a full schema could look like:

type Mutation {
  createUser(name: String!, age: Int!): User!
  createPost(title: String!, author: ID!): Post!
  deletePost(id: ID!): Boolean!

}

type Query {
  getUser(id: ID!): User!
  getPostsByUser(userId: ID!): [Post!]!
}

type Subscription {
  newPost: Post!
}

type User {
  id: ID!
  name: String!
  age: Int!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  author: User!

}

This schema defines types, mutations, queries, and subscriptions for a GraphQL API.

The User type has fields like id, name, age, and posts, showing relationships between types.

Conclusion

In short, GraphQL makes data access easier, keeps data consistent, and supports real-time updates, making it great for modern APIs.

Reference