GraphQL
GraphQL is a query language for APIs and a runtime for executing those queries by describing your data in a robust, flexible schema. Unlike REST, which requires multiple endpoints for different resources, GraphQL exposes a single endpoint and enables clients to request exactly the data they need in a single request.
Key Concepts
- Single Endpoint: All queries and mutations are sent to the same URL.
- Flexible Queries: Clients specify the exact shape of the response, reducing over-fetching or under-fetching of data.
- Strongly Typed Schema: GraphQL APIs are defined by a schema that specifies the types of queries and data available.
Common Operations
| Operation | Usage |
|---|---|
| Query | Read data |
| Mutation | Write/update/delete data |
| Subscription | Receive real-time updates (optional) |
Example Query
Suppose a user object is available via the following GraphQL schema:
type User {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
}
A GraphQL query to get a user's name and email might look like:
query {
user(id: "42") {
name
email
}
}
How It Compares to REST
- No more multiple roundtrips: Fetch related data (e.g., user + posts + comments) in a single query.
- Documentation & Validation: The schema enables introspection and powerful IDEs like GraphiQL or Apollo Studio.
- Client-Driven: The shape of the response is controlled by the client, not the server.
Why GraphQL?
- Useful for clients with complex data needs (mobile apps, dashboards).
- Eases evolution of APIs without versioning.
- Powerful for aggregating data from multiple sources and microservices.
Drawbacks
- More complex to secure (granular authorization required).
- Can be overkill for simple APIs.
- Requires specific tooling and learning curve.
To learn more or get started, see the official docs or explore open-source tools like Apollo Server and GraphQL.js.