REST vs. GraphQL: A Frontend Engineer’s Reality Check
A practical comparison of REST and GraphQL for frontend developers. You write a typed TypeScript data layer for one dashboard against both APIs, then compare them on round trips, over-fetching, HTTP caching, error handling and type safety, with a table and a checklist for choosing between them.

"Should I use REST or GraphQL for my next app?" comes up often in developer communities. Most answers stay theoretical: "resources" versus "graphs", "flexible schemas". That doesn't help when you're staring at an empty editor, trying to design a frontend that doesn't choke on network requests.
This guide is for frontend developers who need to pick one, or work with both. Instead of declaring a winner, you'll build the same data layer twice in TypeScript and compare what each approach costs you in round trips, caching, error handling and typing.
This is part 15 of the Frontend & JavaScript Fundamentals series. It builds on the previous part, CORS, HTTP and web security, because both APIs below are plain HTTP underneath.
Key takeaways
- REST maps each resource to a URL, so you get HTTP caching almost for free but may need several requests per screen.
- GraphQL lets the client ask for exactly the fields it needs in one request, at the cost of more work for caching and error handling.
- Choose per use case: GraphQL suits nested, per-user views with several clients; REST suits simple, public or cache-heavy data. Many systems use both.
The two models in one paragraph each
REST (Representational State Transfer) is a set of architecture constraints for distributed systems. In practice, a "REST API" exposes each resource at its own URL, and you act on it with HTTP methods. MDN notes that many HTTP APIs are called RESTful without following every REST constraint.
GraphQL is, in graphql.org's words, "a query language for your API, and a server-side runtime for executing queries using a type system you define for your data." The client sends one query that names the fields it wants, usually to a single /graphql endpoint.
The scenario: the dashboard problem
To make this a fair comparison, take one scenario: a creator analytics dashboard. It needs:
- The user's profile (name, avatar).
- Their latest 5 projects.
- The total views across those projects.
This is a classic under-fetching case. No single REST endpoint returns everything, so the client has to make several requests. It's sometimes called the "N+1 problem", but graphql.org uses that name for something else: a server that makes one data-source call per item in a list.
Approach 1: the REST implementation
In a typical REST setup, the data lives behind separate endpoints:
GET /api/v1/meGET /api/v1/users/{id}/projects?limit=5
Here is the frontend code with the standard fetch() API. The URLs are relative, as in a frontend served from the same origin as its API. Wrapping the calls in a small typed module keeps your components clean.
// rest-consumer.ts
export interface User {
id: string;
name: string;
avatar: string;
}
export interface Project {
id: string;
name: string;
views: number;
}
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
// fetch() only rejects on network errors; a 404 or 500 still resolves
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText} for ${url}`);
}
return (await response.json()) as T;
}
export async function loadDashboardData() {
try {
// 1. Fetch the user
const user = await getJson<User>('/api/v1/me');
// 2. Fetch projects (waterfall: this needs user.id first)
const projects = await getJson<Project[]>(`/api/v1/users/${user.id}/projects?limit=5`);
// 3. Client-side aggregation
const totalViews = projects.reduce((sum, project) => sum + project.views, 0);
return { user, projects, totalViews };
} catch (error) {
console.error('Failed to load dashboard', error);
throw error;
}
}
Both files in this post were type-checked with typescript@7.0.2 in strict mode and run on Node.js 22 against a stubbed fetch, 2026-10-30. The earlier version didn't check the status code, so a 404 page would have been parsed as a user. getJson() now checks response.ok, which MDN defines as a status in the 200 to 299 range.
The practical pain points
- Waterfall requests: you can't fetch projects until you have the user's id, so the two requests run one after the other. If the endpoints were independent,
Promise.allcould run them in parallel. - Over-fetching: the projects endpoint may return descriptions, dates and metadata this view doesn't need. That's wasted bandwidth.
- Loose typing: the
as Tcast is a promise, not a check. Unless you share types in a monorepo or generate them from an OpenAPI description, the frontend has to trust the response shape.
Approach 2: the GraphQL implementation
GraphQL flips the model. Instead of the server deciding what each endpoint returns, the client asks for exactly the fields it needs, in one request to one endpoint.
// graphql-consumer.ts
import type { User, Project } from './rest-consumer';
const DASHBOARD_QUERY = `
query GetDashboardData {
me {
id
name
avatar
projects(limit: 5) {
id
name
views
}
}
}
`;
interface DashboardResult {
data?: { me: User & { projects: Project[] } } | null;
errors?: { message: string }[];
}
export async function loadDashboardData() {
try {
const response = await fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/graphql-response+json, application/json',
},
body: JSON.stringify({ query: DASHBOARD_QUERY }),
});
// A proxy error page may not be JSON; fall through to the status check
const result = (await response.json().catch(() => ({}))) as DashboardResult;
// Errors can arrive with a 200 status, so check the body as well as the status
if (result.errors?.length) {
throw new Error(result.errors[0].message);
}
if (!response.ok || !result.data) {
throw new Error(`GraphQL request failed with status ${response.status}`);
}
const { me } = result.data;
// Aggregation still happens on the client, unless the schema offers a total field
const totalViews = me.projects.reduce((sum, project) => sum + project.views, 0);
return { user: me, projects: me.projects, totalViews };
} catch (error) {
console.error('GraphQL error', error);
throw error;
}
}
The extensionless import type assumes a bundler setup, such as Vite or TypeScript's moduleResolution: "bundler"; it is removed at build time either way. The Accept header follows graphql.org's advice for clients: ask for the newer application/graphql-response+json type, and keep application/json for older servers. In the test run, the REST version made two requests and the GraphQL version made one, and both returned the same total.
The practical wins
- One round trip: no waterfall. One request gets everything on the screen.
- Precision: you don't get fields you didn't ask for. That helps most on slow mobile connections.
- Generated types: GraphQL Code Generator reads the schema and your queries and writes TypeScript types for them. If the backend renames a field, your build fails, which is what you want.
Analysing the trade-offs
I've built systems with both. The two consumers above show where the real differences are.
1. Caching
REST has the edge. REST uses HTTP the way it was designed. MDN's caching guide explains that caches tell responses apart mainly by URL. A GET /api/v1/users/42/projects response can be stored by the browser and by a CDN, based on its Cache-Control headers.
GraphQL can do this too, but it takes work. Most clients send queries as POST, and as a rule of thumb CDNs don't cache POST responses. graphql.org says a server may also accept GET for queries, which makes HTTP and CDN caching possible. Long queries can hit URL length limits, so graphql.org suggests persisted queries: the client sends a short hash instead of the full query. Many apps also use a client library such as Apollo Client or urql, which keeps a normalized cache in memory. That adds code and bundle size.
For personalised data like this dashboard, the difference shrinks. MDN warns that personalised responses belong in a private cache (Cache-Control: private), not a shared one.
2. Error handling
REST is simpler. In REST, a 404 means not found and a 500 means a server error. Your code checks response.ok or response.status.
In GraphQL, a response that has data should use a 2xx status even when it also contains errors, according to graphql.org, because HTTP has no status for "partial success". So you check the errors array as well as the status, as the code above does. That code throws on any error. If a screen can show partial data, keep data and show the errors next to it instead.
3. Rapid iteration and data shape
GraphQL has the edge. Suppose the design changes and the dashboard now needs each project's description. With REST, you may have to ask the backend team to add the field to the endpoint. With GraphQL, if description already exists in the schema, you add one line to the query. If it doesn't exist yet, the backend still has to add it, but only once for every client.
| REST | GraphQL | |
|---|---|---|
| Requests per screen | Often several | Usually one |
| Response shape | Set by the server per endpoint | Set by the client per query |
| HTTP and CDN caching | Works by default for GET |
Needs GET or persisted queries, often plus a client cache |
| Errors | HTTP status codes | errors array, sometimes with a 200 status |
| Types in TypeScript | Shared types or OpenAPI generators | Code generation from the schema |
| Best fit | Simple, public or cache-heavy data | Nested, per-user views with several clients |
When to use which
Use the comparison above as a rule of thumb, not a law.
Choose REST if:
- The data is flat and simple. For fetching a single blog post, GraphQL is overkill.
- You rely heavily on HTTP caching. For public data cached at the edge, REST is easier.
- You want zero dependencies. A plain
fetch()call works everywhere. - You're building a public API. Third-party developers can call a REST endpoint without first learning your schema.
Choose GraphQL if:
- You have a dashboard-style app. Lots of related, nested data in a per-user view, which a CDN wouldn't cache anyway.
- You have several clients. Web, mobile and partners each need a different shape of the same data.
- Bandwidth matters. Smaller payloads help users on slow mobile networks.
- You use TypeScript. Types generated from a GraphQL schema give you strong end-to-end type safety.
Final thoughts
There is no better architecture, only a better fit. You don't have to choose one for the whole system. A common split is GraphQL for a complex internal dashboard and REST for simple public endpoints such as webhook receivers.
Next in the series, frontend authentication with JWTs and cookies covers how either kind of API knows who is calling.
Frequently asked questions
Is GraphQL faster than REST?
Not by itself. GraphQL can save round trips and bytes, because one query fetches exactly the fields a screen needs. REST can be faster for data that a browser or CDN can cache. Measure your own screens rather than relying on the label.
Can GraphQL responses be cached by a CDN?
Yes, with some setup. graphql.org says servers may accept GET for queries, which CDNs can cache when the response has caching headers. Persisted queries keep those URLs short by sending a hash instead of the full query.
Why does my GraphQL API return 200 when there is an error?
A GraphQL response can contain both data and errors. graphql.org says a response with non-null data should use a 2xx status, because HTTP has no "partial success" status. Always check the errors array, not just the status code.
Can I use REST and GraphQL in the same project?
Yes, and many projects do. A GraphQL layer can sit in front of existing REST services, and simple or public endpoints can stay REST. Pick per use case, not per company.
Do I need Apollo Client to use GraphQL?
No. As the example above shows, a GraphQL request is a normal HTTP request you can send with fetch(). Client libraries such as Apollo Client or urql add caching and other features, which help in larger apps.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...