Sobes.tech
Junior

What is GraphQL?

sobes.tech AI

Answer from AI

GraphQL is a query language for APIs and a runtime environment for executing those queries against your data. It offers an alternative to REST, allowing clients to request only the data they need in a single request.

Key concepts:

  1. Schema: Defines the data types available in the API, their relationships, and available operations (queries, mutations, subscriptions).
  2. Queries: Used for reading data. The client specifies which fields it needs.
  3. Mutations: Used for modifying data (creating, updating, deleting).
  4. Subscriptions: Used for receiving real-time data via a persistent connection (e.g., WebSocket).

Example query:

query GetUserData {
  user(id: "123") {
    name
    email
    posts {
      title
    }
  }
}

The response to this query might look like:

{
  "data": {
    "user": {
      "name": "Ivan",
      "email": "ivan@example.com",
      "posts": [
        { "title": "My first article" },
        { "title": "About GraphQL" }
      ]
    }
  }
}

Advantages over REST:

  • Avoiding over-fetching: The client receives only the fields it requests.
  • Avoiding under-fetching / multiple requests: Often allows obtaining all necessary information in one request, unlike REST, which may require multiple requests to different endpoints.
  • Strong typing: The schema provides clear documentation and validation of requests.
  • Improved performance: Less data transmitted.
  • Client-side flexibility: Clients can evolve independently from the server, requesting data as needed.

Disadvantages:

  • Complexity of server-side setup.
  • Caching issues compared to standard REST caching methods (e.g., at the HTTP level).
  • More complex error handling compared to REST (which uses standard HTTP statuses).