Understanding GraphQL Core Concepts

1. Understanding GraphQL vs REST

AspectGraphQLREST
EndpointsSingle /graphqlMultiple resource URLs
Data FetchingClient selects exact fieldsServer returns fixed shape
Over/Under-fetchingEliminatedCommon problem
VersioningSchema evolution + @deprecatedURL/header versioning (v1, v2)
HTTP MethodsPOST (typically)GET/POST/PUT/PATCH/DELETE
CachingApp-level (Apollo, urql)HTTP cache (built-in)
Type SystemStrongly typed schema (SDL)Optional (OpenAPI)
Errors200 OK + errors[]HTTP status codes
Real-timeSubscriptions built-inSSE/WebSocket add-on
File Uploadmultipart spec extensionmultipart/form-data native

2. Understanding Query Language Concepts

ConceptSyntaxPurpose
Operationquery | mutation | subscriptionTop-level request type
Selection Set{ field1 field2 }Fields requested from a type
Fieldname(arg: val)Unit of data, may take args
Aliasnick: nameRename in response JSON
Fragment...UserFieldsReusable selection set
Variable$id: ID!Parameterize the operation
Directive@include(if: $b)Modify execution

3. Understanding Type System

CategoryExamplesDescription
ScalarInt Float String Boolean IDLeaf primitive values
Objecttype User { id: ID! }Composite output type
Inputinput UserInput { ... }Argument-only object
Enumenum Role { ADMIN USER }Fixed value set
Interfaceinterface Node { id: ID! }Abstract shared fields
Unionunion Result = A | BOne of several object types
List[Type]Ordered collection
Non-nullType!Required modifier

4. Understanding Schema-first Design

ApproachDescriptionTools
Schema-first (SDL)Write SDL, then implement resolversApollo Server, GraphQL Tools
Code-firstDefine types in code, generate SDLPothos, Nexus, TypeGraphQL
Database-firstGenerate schema from DBHasura, PostGraphile

5. Understanding Resolver Pattern

ArgumentTypeDescription
parent / root / sourceObjectResult from parent field's resolver
argsObjectArguments passed to the field
contextObjectPer-request shared state (auth, loaders)
infoGraphQLResolveInfoAST, 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

  1. Parse: Query string → AST
  2. Validate: AST checked against schema rules
  3. Execute: Walk selection set, invoke resolvers depth-first
  4. Resolve: Each field resolver returns value/promise
  5. Format: Build response { data, errors, extensions }
PhaseFailure Mode
ParseSyntax error → no execution
ValidateSchema error → no execution
ExecuteResolver error → null + errors[]

7. Understanding Single Endpoint Architecture

AspectDetail
URLSingle /graphql endpoint
MethodPOST with JSON body, GET for queries (cacheable)
RoutingOperation type + selection determines work
CDN cachingUse 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}               │
  │◀───────────────────────────────│
      
FieldBody
queryString SDL operation
variablesJSON object of typed values
operationNamePicks one when document has multiple

9. Understanding GraphQL Advantages

BenefitWhy
No over-fetchingClient picks fields
Strong typingCodegen, autocomplete, validation
Single round-tripMultiple resources in one request
Self-documentingIntrospection drives docs/tools
Versionless evolutionAdd fields, deprecate old ones

10. Understanding GraphQL Trade-offs

DrawbackMitigation
N+1 queriesDataLoader batching
HTTP caching hardAPQ + GET, edge caching by hash
Complexity attacksDepth/cost limits, persisted queries
File uploads non-trivialmultipart spec or signed URLs
Server complexitySchema-first frameworks, codegen