Understanding GraphQL Core Concepts
1. Understanding GraphQL vs REST
| Aspect | GraphQL | REST |
|---|---|---|
| Endpoints | Single /graphql | Multiple resource URLs |
| Data Fetching | Client selects exact fields | Server returns fixed shape |
| Over/Under-fetching | Eliminated | Common problem |
| Versioning | Schema evolution + @deprecated | URL/header versioning (v1, v2) |
| HTTP Methods | POST (typically) | GET/POST/PUT/PATCH/DELETE |
| Caching | App-level (Apollo, urql) | HTTP cache (built-in) |
| Type System | Strongly typed schema (SDL) | Optional (OpenAPI) |
| Errors | 200 OK + errors[] | HTTP status codes |
| Real-time | Subscriptions built-in | SSE/WebSocket add-on |
| File Upload | multipart spec extension | multipart/form-data native |
2. Understanding Query Language Concepts
| Concept | Syntax | Purpose |
|---|---|---|
| Operation | query | mutation | subscription | Top-level request type |
| Selection Set | { field1 field2 } | Fields requested from a type |
| Field | name(arg: val) | Unit of data, may take args |
| Alias | nick: name | Rename in response JSON |
| Fragment | ...UserFields | Reusable selection set |
| Variable | $id: ID! | Parameterize the operation |
| Directive | @include(if: $b) | Modify execution |
3. Understanding Type System
| Category | Examples | Description |
|---|---|---|
| Scalar | Int Float String Boolean ID | Leaf primitive values |
| Object | type User { id: ID! } | Composite output type |
| Input | input UserInput { ... } | Argument-only object |
| Enum | enum Role { ADMIN USER } | Fixed value set |
| Interface | interface Node { id: ID! } | Abstract shared fields |
| Union | union Result = A | B | One of several object types |
| List | [Type] | Ordered collection |
| Non-null | Type! | Required modifier |
4. Understanding Schema-first Design
| Approach | Description | Tools |
|---|---|---|
| Schema-first (SDL) | Write SDL, then implement resolvers | Apollo Server, GraphQL Tools |
| Code-first | Define types in code, generate SDL | Pothos, Nexus, TypeGraphQL |
| Database-first | Generate schema from DB | Hasura, PostGraphile |
5. Understanding Resolver Pattern
| Argument | Type | Description |
|---|---|---|
| parent / root / source | Object | Result from parent field's resolver |
| args | Object | Arguments passed to the field |
| context | Object | Per-request shared state (auth, loaders) |
| info | GraphQLResolveInfo | AST, path, schema metadata |
Example: Resolver signature
const resolvers = {
Query: {
user: async (parent, args, context, info) => {
return context.db.user.findUnique({ where: { id: args.id } });
}
}
};
6. Understanding GraphQL Execution
Execution Pipeline
- Parse: Query string → AST
- Validate: AST checked against schema rules
- Execute: Walk selection set, invoke resolvers depth-first
- Resolve: Each field resolver returns value/promise
- Format: Build response
{ data, errors, extensions }
| Phase | Failure Mode |
|---|---|
| Parse | Syntax error → no execution |
| Validate | Schema error → no execution |
| Execute | Resolver error → null + errors[] |
7. Understanding Single Endpoint Architecture
| Aspect | Detail |
|---|---|
| URL | Single /graphql endpoint |
| Method | POST with JSON body, GET for queries (cacheable) |
| Routing | Operation type + selection determines work |
| CDN caching | Use persisted queries + GET for HTTP cacheability |
8. Understanding Request-Response Flow
Client HTTP Server
│ POST /graphql │
├──{query, variables}───────────▶│
│ parse │
│ validate │
│ execute─┼──▶ resolvers ──▶ data sources
│ {data, errors} │
│◀───────────────────────────────│
| Field | Body |
|---|---|
| query | String SDL operation |
| variables | JSON object of typed values |
| operationName | Picks one when document has multiple |
9. Understanding GraphQL Advantages
| Benefit | Why |
|---|---|
| No over-fetching | Client picks fields |
| Strong typing | Codegen, autocomplete, validation |
| Single round-trip | Multiple resources in one request |
| Self-documenting | Introspection drives docs/tools |
| Versionless evolution | Add fields, deprecate old ones |
10. Understanding GraphQL Trade-offs
| Drawback | Mitigation |
|---|---|
| N+1 queries | DataLoader batching |
| HTTP caching hard | APQ + GET, edge caching by hash |
| Complexity attacks | Depth/cost limits, persisted queries |
| File uploads non-trivial | multipart spec or signed URLs |
| Server complexity | Schema-first frameworks, codegen |