> For the complete documentation index, see [llms.txt](https://everythingblackkk.gitbook.io/everythingblackkk/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://everythingblackkk.gitbook.io/everythingblackkk/web-development-and-technologies/what-is-graphql-1.md).

# What is GraphQL ?

<figure><img src="/files/W04JkBWnfX0cps3DlHha" alt=""><figcaption></figcaption></figure>

## GraphQL Type System and Schema Definition Language (SDL)

GraphQL uses its **own type system** to define the schema of an API. The specific syntax used for writing schemas is called the **Schema Definition Language (SDL)**.

> You Can Learn more about (SDL) From This Link->&#x20;

{% embed url="<https://www.apollographql.com/tutorials/lift-off-part1/03-schema-definition-language-sdl>" %}

**Defining Types and Fields:** You can define simple types using SDL. For example, the sources show a `Person` type and a `Post` type.

```graphql
type Person {
  name: String!
  age: Int!
}
```

* The `Person` type has two fields: `name` (of type `String`) and `age` (of type `Int`).
* The `Post` type has one field: `title` (of type `String`).

```graphql
type Post {
  title: String!
  author: Person!
}
```

* An **exclamation point** (`!`) after a type indicates that the field is **required**.

**Defining Relationships (Relations):** GraphQL allows you to express relationships between types. A common relationship is a **one-to-many relationship**, such as one person being the author of many posts.

* To set up this relationship, an `author` field is added to the `Post` type, linking every post to a specific person.
* A `posts` field is added to the `Person` type.
* To specify that a field represents a **list** (like a list of posts), square brackets are used in the SDL, similar to many programming languages.

#### Fetching Data with Queries

> We Talk About The differential between GraphQL & REST API From ->

{% embed url="<https://everythingblackkk.gitbook.io/everythingblackkk/web-development-and-technologies/graphql-vs-rest>" %}

\
When working with GraphQL, the approach for fetching data is different from traditional REST APIs.

* **REST APIs** load data from multiple specific endpoints, and each endpoint returns a fixed data structure.
* **GraphQL APIs** typically expose only a **single endpoint**. The structure of the returned data is flexible, allowing the client to decide exactly what data is needed.

The information a client sends to the server to express its data needs is called a **query**.

**Query Structure:** A query has two main parts:

1. The **root field** (e.g., `allPersons`).
2. The **payload**, which is everything that follows the root field.

The server response is shaped exactly according to the fields specified in the query's payload. If the payload only asks for the `name`, the server will only return the `name` and not the `age`. If the client needs the `age`, they simply adjust the query and include the `age` field in the payload.

**Query Arguments:** Each field in a GraphQL query can have zero or more **arguments**, provided they are defined in the schema. For example, the `allPersons` field might use a `last` parameter to limit the number of persons returned.

**Querying Nested Information:** A major advantage of GraphQL is its ability to naturally query **nested information**. If you want to load the list of posts that each person has written, you can simply follow the structure of your types in the query. The server will then resolve the query and include the list of associated posts in the response.

#### Making Changes with Mutations

Most applications require ways to make changes to the data stored in the back end. In GraphQL, these changes are handled using **mutations**.

There are generally three types of mutations: creating new data, updating existing data, and deleting existing data.

**Mutation Syntax and Structure:** Mutations follow the same basic structure as queries, but they **must always start with the `mutation` keyword**.

* They have a **root field** (e.g., `createPerson`).
* The root field often takes **arguments** that specify the data for the change (e.g., the new person's name and age).
* Like queries, mutations can specify a **payload**. The client can use this payload to retrieve new information from the server in a single network trip.
* This is especially powerful for retrieving information generated by the server, such as a **unique ID** for a newly created object, which was not available on the client beforehand.
* The server response to a mutation is shaped according to the payload sent in the mutation.

### **GraphQL Mutations Ex**

In GraphQL, **mutations** are used to **modify data** on the server , like creating, updating, or deleting records.\
They work similarly to queries but change data instead of just fetching it.

**Example (GraphQL mutation):**

```graphql
mutation {
  createUser(name: "John", email: "john@example.com") {
    id
    name
    email
  }
}
```

* This mutation creates a new user and returns the user’s `id`, `name`, and `email`.

***

#### **REST API Equivalent**

In REST, modifying data is done using **HTTP methods** like:

* `POST` → create
* `PUT` or `PATCH` → update
* `DELETE` → remove

**Example (REST request):**

```http
POST /users
Content-Type: application/json

{
  "name": "John",
  "email": "john@example.com"
}
```

* This `POST` request creates a new user, similar to the GraphQL mutation above.

***

#### Real-time Data with Subscriptions

For applications requiring a real-time connection to the server to be immediately informed about important events, GraphQL offers the concept of **subscriptions**.

* When a client subscribes to an event (e.g., `newPerson` being created), it starts and maintains a **steady connection** to the server.
* When that specific event occurs, the server **pushes** the corresponding data to the client.
* The data pushed is based on the information specified in the subscription payload (e.g., the name and age of the new user).
* Unlike queries and mutations, which follow a typical request-response cycle, subscriptions represent a **stream of data** sent to the client. If three persons are created by other clients while the subscription is active, the server pushes the data for each of those three persons to the subscribed client.

### **Example (GraphQL subscription):**

```graphql
subscription {
  newMessage {
    id
    text
    sender
  }
}

```

* This keeps the client listening , whenever a new message is created, the server pushes it instantly to the client.

> In REST API You Must Useustom implementations for real-time updates Like :&#x20;

* Use **SSE** if you need **continuous updates from the server only** (like notifications or a live feed).
* Use **WebSocket** if you need **two-way interaction** or **frequent, high-speed updates** (like chat applications or online games).

<figure><img src="/files/04ZHAhKfw4zIdSeyLyzd" alt=""><figcaption></figcaption></figure>

#### Defining the Schema: Root Types

The schema is considered one of the most important concepts when working with a GraphQL API, often acting as a **contract** between the server and the client. It defines the API's capabilities and how data can be fetched and updated.

A schema is fundamentally a collection of GraphQL types. However, every schema must include specific **root types** that define the entry points for the API:

1. The **Query** type.
2. The **Mutation** type.
3. The **Subscription** type

```graphql
type Query { ... }
type Mutation { ... }
type Subscription { ... }.
```

**Mapping Operations to Root Types:** To enable operations like those demonstrated earlier, corresponding fields must be added to these root types.

* **Query Type:** The `allPersons` field must be added to the Query type. This field returns a list of persons, and it may include arguments like `last` to limit the number of users.
* **Mutation Type:** The `createPerson` field must be added to the Mutation type. It takes arguments (like `name` and `age`) and returns a single `Person` object—the one that was created.
* **Subscription Type:** The `newPerson` field must be added to the Subscription type. This field allows clients to subscribe to the event of new persons being created, and its type is `Person`.

```graphql
type Query {
  allPersons(last: Int): [Person!]!
  allPosts(last: Int): [Post!]!
}

type Mutation {
  createPerson(name: String!, age: Int!): Person!
  updatePerson(id: ID!, name: String!, age: Int!): Person!
  deletePerson(id: ID!): Person!
}

type Subscription {
  newPerson: Person!
}

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

type Post {
  title: String!
  author: Person!
}

```

## Some Resource :&#x20;

* <https://www.howtographql.com/basics/2-core-concepts/>
* <https://www.apollographql.com/tutorials/lift-off-part1/03-schema-definition-language-sdl>
* <https://www.youtube.com/watch?v=sYJy7sOz_Sw>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://everythingblackkk.gitbook.io/everythingblackkk/web-development-and-technologies/what-is-graphql-1.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
