100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

GraphQL vs REST for Data Access Cheat Sheet

GraphQL vs REST for Data Access Cheat Sheet

Compares GraphQL and REST for data-fetching patterns, covering over/under-fetching, endpoint design, caching, and N+1 query pitfalls.

2 PagesIntermediateMar 5, 2026

Request Comparison

Fetching related data with REST versus GraphQL.

javascript
// REST: multiple round trips to avoid over-fetching, or one bloated endpoint// GET /api/users/42// GET /api/users/42/posts// GET /api/posts/17/comments// GraphQL: one request, client specifies exactly the fields it needsconst query = `  query {    user(id: 42) {      name      posts {        title        comments {          text        }      }    }  }`;const res = await fetch('/graphql', {  method: 'POST',  headers: { 'Content-Type': 'application/json' },  body: JSON.stringify({ query }),});

Trade-offs

How the two approaches differ in practice.

  • Over-fetching- REST endpoints often return fixed shapes with more fields than the client needs; GraphQL clients request exact fields
  • Under-fetching- REST may require multiple round trips to assemble related data; GraphQL resolves nested relations in a single request
  • Caching- REST benefits from standard HTTP caching (ETag, Cache-Control, CDNs) keyed by URL; GraphQL POST requests need custom client-side caching (Apollo, Relay normalized cache)
  • Versioning- REST typically versions endpoints (/v1, /v2); GraphQL favors additive schema evolution with field deprecation instead of versioning
  • Error handling- REST uses HTTP status codes per request; GraphQL usually returns 200 with an errors array, requiring clients to check payload-level errors
  • Tooling- GraphQL ships a strongly typed schema enabling introspection, codegen, and interactive explorers (GraphiQL); REST relies on external specs like OpenAPI for the same

Avoiding N+1 with DataLoader

Batch per-request lookups into a single query.

javascript
const DataLoader = require('dataloader');// Batches individual post.author lookups into one SQL query per tickconst userLoader = new DataLoader(async (userIds) => {  const users = await db.query(    'SELECT * FROM users WHERE id = ANY($1)',    [userIds]  );  const byId = Object.fromEntries(users.map((u) => [u.id, u]));  return userIds.map((id) => byId[id]);});const resolvers = {  Post: {    author: (post) => userLoader.load(post.authorId),  },};

When to Use Which

Guidance for picking an API style for data access.

  • Choose REST when- You need simple CRUD, strong HTTP caching, public/partner APIs, or your clients' data needs are uniform and stable
  • Choose GraphQL when- Clients have diverse, evolving data needs (e.g., web + mobile with different field requirements), or you're aggregating multiple backend services
  • Hybrid approach- Many teams expose REST for simple public endpoints and GraphQL (or a BFF) for complex, client-driven aggregation
  • Team/ops cost- GraphQL requires more upfront investment: schema design, resolver N+1 mitigation, query complexity/depth limiting to prevent abuse

Persisted Queries

Ship a hash instead of the raw query string to cut payload size and block arbitrary query abuse.

javascript
// Build time: generate a manifest of query -> sha256 hash// { "a1b2c3...": "query GetUser($id: ID!) { user(id: $id) { name } }" }// Client sends only the hash, not the full query textconst res = await fetch('/graphql', {  method: 'POST',  headers: { 'Content-Type': 'application/json' },  body: JSON.stringify({    extensions: {      persistedQuery: {        version: 1,        sha256Hash: 'a1b2c3...',      },    },    variables: { id: 42 },  }),});// Server: reject any request whose hash isn't in the allowlist// (APQ - Automatic Persisted Queries, or a strict allowlist for prod)if (!persistedQueryManifest.has(sha256Hash)) {  throw new Error('PersistedQueryNotFound');}

Query Complexity & Depth Limiting

Reject expensive or deeply nested queries before execution to prevent denial-of-service via GraphQL.

javascript
const { createComplexityLimitRule } = require('graphql-validation-complexity');const depthLimit = require('graphql-depth-limit');const server = new ApolloServer({  schema,  validationRules: [    depthLimit(7), // reject queries nested deeper than 7 levels    createComplexityLimitRule(1000, {      // assign per-field cost, e.g. list fields cost more      scalarCost: 1,      objectCost: 2,      listFactor: 10,      onCost: (cost) => console.log('query cost:', cost),    }),  ],});// Field-level cost directive in schema// type Query {//   users(first: Int): [User!]! @cost(complexity: 10, multipliers: ["first"])// }

HATEOAS-Style REST Response

A REST response embedding hypermedia links so clients discover valid next actions without hardcoding URLs.

json
{  "id": 42,  "status": "pending",  "total_cents": 4999,  "_links": {    "self": { "href": "/api/orders/42" },    "cancel": { "href": "/api/orders/42/cancel", "method": "POST" },    "items": { "href": "/api/orders/42/items" },    "customer": { "href": "/api/customers/17" }  }}

GraphQL Gotchas at Scale

Issues that only surface once GraphQL is serving real production traffic.

  • HTTP caching bypass- POST-based GraphQL requests skip browser/CDN HTTP caching entirely; GET-based persisted queries with query params can restore CDN cacheability
  • File uploads- The spec has no native multipart support; teams bolt on graphql-multipart-request-spec or move uploads to a separate REST/presigned-URL endpoint
  • Field-level authorization drift- Because any client can request any field combination, authorization must be enforced per-resolver/per-field, not just per-endpoint like REST
  • Response size explosion- A single query can traverse many-to-many relations and return megabytes of nested data; pagination (cursor-based, Relay connections) must be mandatory on list fields
  • Schema stitching vs federation- Combining multiple GraphQL services requires either schema stitching (deprecated pattern) or Apollo Federation/GraphQL Federation with entity resolution across subgraphs
  • Caching invalidation- Normalized client caches (Apollo, Relay) key entities by __typename + id; mutations must return the updated fields so the cache can reconcile without a full refetch

Real-Time Data with Subscriptions

GraphQL's third operation type for push-based updates, an area REST has no standard answer for.

graphql
type Subscription {  orderStatusChanged(orderId: ID!): Order!}# Client (over WebSocket via graphql-ws)subscription OnOrderStatus($orderId: ID!) {  orderStatusChanged(orderId: $orderId) {    id    status    updatedAt  }}# Resolver publishes to a topic-based PubSub on mutationconst resolvers = {  Mutation: {    updateOrderStatus: async (_, { id, status }, { pubsub }) => {      const order = await db.orders.update(id, { status });      pubsub.publish(`ORDER_${id}`, { orderStatusChanged: order });      return order;    },  },  Subscription: {    orderStatusChanged: {      subscribe: (_, { orderId }, { pubsub }) =>        pubsub.asyncIterator(`ORDER_${orderId}`),    },  },};
Pro Tip

GraphQL's flexibility is also its biggest operational risk — without query depth limiting, complexity analysis, and persisted queries, a single malicious or buggy client query can fan out into thousands of database calls; treat query cost limiting as a launch requirement, not an afterthought.

Was this cheat sheet helpful?

Explore Topics

#GraphQLVsRESTForDataAccess#GraphQLVsRESTForDataAccessCheatSheet#Database#Intermediate#RequestComparison#TradeOffs#AvoidingN1WithDataLoader#WhenToUseWhich#Databases#APIs#CheatSheet#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse