Technologia

GraphQL

Język zapytań do API. Pobieraj dokładnie to, czego potrzebujesz — nic więcej, nic mniej.

Czym jest GraphQL?

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.

Przykłady kodu

Schema Definition

GraphQL Schema 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 — klient pobiera co chce

GraphQL Query 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

React + Apollo Client

React + Apollo 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} /> ); }

Ocena kompetencji

Elastyczność zapytań
100%
Type safety
98%
DX
90%
Caching
70%
Prostota
60%
Łatwość nauki
65%

Co potrafi GraphQL

Precise data fetching

Klient definiuje strukturę odpowiedzi. Zero over-fetching, zero under-fetching.

Typed Schema

Schema = kontrakt. Auto-generated types, introspection, dokumentacja z kodu.

Subscriptions

Real-time updates przez WebSocket. Chat, notifications, live dashboards.

Jeden endpoint

POST /graphql. Koniec z dziesiątkami REST endpoints. Łatwiejsze zarządzanie.

Code generation

graphql-codegen → TypeScript types, React hooks, SDK. Full type safety.

Federation

Apollo Federation. Mikroserwisy z jednym unified GraphQL API.

Kiedy wybrać GraphQL?

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).