Definition
GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. Unlike REST, which uses multiple endpoints for different resources, GraphQL provides a single endpoint and allows clients to request exactly the data they need, and nothing more.
Why It Matters
GraphQL solves the problems of over-fetching (receiving too much data) and under-fetching (needing to make multiple requests). This precision makes applications faster and more efficient, especially on mobile networks or for complex frontends that require data from multiple related sources.
Core Concepts
- Single Endpoint: All requests are sent to a single URL (typically a POST request).
- Declarative Data Fetching: The client defines the structure of the response.
- Strongly Typed Schema: The API defines the types of data available, which serves as a contract between frontend and backend.
- Queries and Mutations: “Queries” are used for reading data; “Mutations” are used for writing/updating data.
// Example: A GraphQL Query to fetch specific fields
query {
user(id: "123") {
name
email
profilePicture
}
}