GraphQL to język zapytań do API stworzony przez Meta (Facebook) w 2012 roku. W przeciwieństwie do REST, gdzie serwer decyduje co zwrócić, w GraphQL klient definiuje dokładną strukturę danych, którą chce otrzymać.
GraphQL eliminuje over-fetching (za dużo danych) i under-fetching (za mało danych). Jeden endpoint, typed schema, real-time subscriptions. Używany przez GitHub, Shopify, Hasura, Apollo.
type User {
id: ID!
name: String!
email: String!
avatar: String
orders: [Order!]!
createdAt: DateTime!
}
type Order {
id: ID!
total: Float!
status: OrderStatus!
items: [OrderItem!]!
}
enum OrderStatus {
PENDING
PROCESSING
COMPLETED
CANCELLED
}
type Query {
user(id: ID!): User
users(limit: Int, offset: Int): [User!]!
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
}
query GetUserWithOrders($id: ID!) {
user(id: $id) {
name
email
orders {
id
total
status
items {
name
quantity
price
}
}
}
}
# Jeden request zamiast:
# GET /api/users/123
# GET /api/users/123/orders
# GET /api/orders/456/items
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers($limit: Int!) {
users(limit: $limit) {
id
name
avatar
}
}
`;
function UserList() {
const { data, loading, error } = useQuery(GET_USERS, {
variables: { limit: 20 },
});
if (loading) return <Skeleton />;
if (error) return <Error message={error.message} />;
return data.users.map(u =>
<UserCard key={u.id} user={u} />
);
}
Klient definiuje strukturę odpowiedzi. Zero over-fetching, zero under-fetching.
Schema = kontrakt. Auto-generated types, introspection, dokumentacja z kodu.
Real-time updates przez WebSocket. Chat, notifications, live dashboards.
POST /graphql. Koniec z dziesiątkami REST endpoints. Łatwiejsze zarządzanie.
graphql-codegen → TypeScript types, React hooks, SDK. Full type safety.
Apollo Federation. Mikroserwisy z jednym unified GraphQL API.
Idealny gdy: masz złożone relacje między danymi, wiele klientów (web, mobile, API), potrzebujesz elastycznych zapytań, budujesz dashboard z wieloma widokami.
Nie najlepszy gdy: budujesz prosty CRUD (lepiej REST), masz prosty backend z kilkoma endpoints, nie chcesz dodatkowej złożoności (lepiej tRPC).