GraphQL
GraphQL is a query language for APIs and a runtime for executing those queries with your existing data.
Tools for implementing GraphQL include GraphQL.js, Apollo and Relay.
Features:
- Declarative Data Fetching: Clients can request exactly the data they need
- Versionless API: Fields can be added without breaking existing queries
- Single Endpoint: Handles all requests (unlike REST APIs)
- Real-time Capabilities: Clients can subscribe for updates when data changes
- Strongly Typed Schema: Specifies types of data that can be queried
- Introspection: Clients can query the schema (making the API self-documenting)
Use Cases:
- Aggregation of data from multiple sources
- Minimization of over-fetching or under-fetching of data
- API needs to evolve over time without breaking existing clients
Basic Example
Query:
{ user(id: "1") { name email posts(limit: 2) { title content } } }
Response:
{ "data": { "user": { "name": "John Doe", "email": "john@example.com", "posts": [ { "title": "GraphQL Basics", "content": "This is a post about GraphQL." }, { "title": "Advanced GraphQL", "content": "This is a post about advanced GraphQL topics." } ] } } }