
REST and GraphQL are both ways for clients to fetch and change data over HTTP, but they make different trade-offs about who decides the shape of the response, how caching works and where complexity lives. Choosing between them, or deciding to use both, affects mobile performance, backend load, team workflow and security. This guide compares them with side-by-side code, explains caching, the N+1 problem and versioning in practical terms, and gives you a decision framework grounded in the network and skills realities of East African teams.
Key takeaways
- REST exposes many resource-oriented endpoints; GraphQL exposes a single endpoint where clients request exactly the fields they need.
- GraphQL reduces over-fetching and multiple round-trips, which helps mobile clients on high-latency networks, but shifts complexity to the server.
- REST benefits from standard HTTP caching (CDNs, browsers,
ETag); GraphQL usually needs application-level or persisted-query caching. - The N+1 query problem is a common GraphQL performance trap; batching with a DataLoader-style pattern is the standard fix.
- REST APIs typically version through URLs; GraphQL evolves a single schema with deprecations.
- For public APIs, partner integrations and simple CRUD, REST remains the pragmatic default. GraphQL shines for complex, client-driven UIs aggregating many data sources.
The core difference
With REST, the server defines a set of resources and endpoints, and each endpoint returns a fixed representation. If you want an order, its customer and its items, you may call three endpoints, or the API designer may have created a composite endpoint for that view.
With GraphQL, the server publishes a typed schema describing all available data and operations. The client sends a query specifying exactly which fields it wants, possibly across related types, and receives a JSON response in the same shape. The specification and documentation live at graphql.org; GraphQL was developed at Facebook and open sourced in 2015, and is now governed by the GraphQL Foundation.
If you are new to REST concepts such as methods and status codes, start with What Is a REST API? A Beginner's Guide.
Readable, typed code is what keeps a front end maintainable as the team grows.
Side-by-side: fetching an order screen
Imagine a mobile app screen showing an order with the customer's name, line items with product names, and M-Pesa payment status.
REST approach
# 1. Fetch the order
curl -H "Authorization: Bearer $TOKEN" https://api.example.co.ke/v1/orders/10045
# 2. Fetch the customer
curl -H "Authorization: Bearer $TOKEN" https://api.example.co.ke/v1/customers/42
# 3. Fetch the payment(s) for the order
curl -H "Authorization: Bearer $TOKEN" "https://api.example.co.ke/v1/payments?order_id=10045"
The order response might contain dozens of fields the screen does not need (over-fetching), and product names may require yet more calls (under-fetching). On a mobile connection with high round-trip latency, sequential calls add up. A well-designed REST API mitigates this with options like ?include=customer,items.product or ?fields=id,status,total, but these are conventions each API implements differently.
GraphQL approach
query OrderScreen($id: ID!) {
order(id: $id) {
id
status
total { amount currency }
customer { name }
items {
quantity
product { name sku }
}
payments {
method
mpesaReceipt
status
}
}
}
Sent as a single request:
curl -X POST https://api.example.co.ke/graphql \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"query":"query OrderScreen($id: ID!) { order(id: $id) { id status customer { name } } }","variables":{"id":"10045"}}'
The response mirrors the query shape exactly, with no unused fields.
Server side: a minimal implementation of each
REST with Express (TypeScript):
import express from "express";
import { db } from "./db"; // your data access layer
const app = express();
app.get("/v1/orders/:id", async (req, res) => {
const order = await db.orders.findById(req.params.id);
if (!order) {
res.status(404).json({ title: "Order not found", status: 404 });
return;
}
res.json(order);
});
app.get("/v1/customers/:id", async (req, res) => {
const customer = await db.customers.findById(req.params.id);
if (!customer) {
res.status(404).json({ title: "Customer not found", status: 404 });
return;
}
res.json(customer);
});
app.listen(3000);
GraphQL with Apollo Server (TypeScript):
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { db } from "./db";
const typeDefs = `#graphql
type Money { amount: String! currency: String! }
type Customer { id: ID! name: String! }
type Product { id: ID! name: String! sku: String! }
type OrderItem { quantity: Int! product: Product! }
type Payment { method: String! mpesaReceipt: String status: String! }
type Order {
id: ID!
status: String!
total: Money!
customer: Customer!
items: [OrderItem!]!
payments: [Payment!]!
}
type Query { order(id: ID!): Order }
`;
const resolvers = {
Query: {
order: (_: unknown, { id }: { id: string }) => db.orders.findById(id),
},
Order: {
customer: (order: { customerId: string }) => db.customers.findById(order.customerId),
items: (order: { id: string }) => db.orderItems.findByOrderId(order.id),
payments: (order: { id: string }) => db.payments.findByOrderId(order.id),
},
OrderItem: {
product: (item: { productId: string }) => db.products.findById(item.productId),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`GraphQL ready at ${url}`);
Notice the GraphQL server has resolvers per field relationship. That flexibility is powerful, and it is exactly where the N+1 problem comes from.
The N+1 problem
In the resolver above, OrderItem.product runs once per item. An order with 20 items triggers 1 query for the items and 20 separate product queries: N+1. Request a list of 50 orders, each with items and customers, and the query count multiplies quickly.
REST APIs can suffer from N+1 inside endpoint handlers too, but GraphQL makes it easier to trigger because clients decide which nested relationships to load.
The standard fix is batching. The dataloader library collects all keys requested during one tick of the event loop and fetches them in a single query:
import DataLoader from "dataloader";
import { db } from "./db";
type Product = { id: string; name: string; sku: string };
// Create a new loader per request so caching never leaks between users.
export function createLoaders() {
return {
productById: new DataLoader<string, Product | null>(async (ids) => {
const rows: Product[] = await db.products.findByIds([...ids]); // one SELECT ... WHERE id IN (...)
const byId = new Map(rows.map((p) => [p.id, p]));
return ids.map((id) => byId.get(id) ?? null); // must return results in the same order as ids
}),
};
}
// In the resolver, read the loader from per-request context:
// OrderItem: { product: (item, _args, ctx) => ctx.loaders.productById.load(item.productId) }
Other safeguards for GraphQL servers:
- Query depth and complexity limits to stop clients from requesting deeply nested, expensive queries.
- Persisted queries, where clients send a hash of a pre-registered query instead of arbitrary text. This also improves caching and reduces request size.
- Monitoring at the resolver level, so you can see which fields are slow.
Caching
REST
REST aligns with HTTP caching. A GET /v1/products/123 response can carry Cache-Control: public, max-age=300 and an ETag. Browsers, mobile HTTP clients, reverse proxies and CDNs all understand these headers. For catalogue data, exchange rates or branch lists, this can remove most load from your servers and reduce data usage for mobile users.
GraphQL
Most GraphQL requests are POSTs to a single URL, so generic HTTP caches cannot distinguish them. Options include:
- Client-side normalised caches (for example in Apollo Client or Relay), which store objects by type and ID and reuse them across queries.
- Persisted queries over GET, which make responses cacheable by CDNs.
- Server-side response or resolver caching, with careful attention to per-user data.
Caching in GraphQL is achievable but requires deliberate design; with REST much of it comes from standard infrastructure.
Versioning and evolution
REST APIs commonly version with a URL prefix (/v1, /v2) or a header. Breaking changes go into a new version and old versions are deprecated over time. This is explicit and easy for partners to understand, but can lead to maintaining multiple versions.
GraphQL encourages continuous evolution of a single schema. You add new fields freely (clients only receive fields they ask for), mark old fields with @deprecated(reason: "..."), monitor usage and remove them once unused. This works well when you control the clients, such as your own web and mobile apps. For external consumers you cannot coordinate with, removal still requires communication and long deprecation windows.
Errors and status codes
REST uses HTTP status codes to signal outcomes. GraphQL commonly returns HTTP 200 even when some fields failed, with an errors array alongside partial data. This allows partial success, which is useful when one backend is slow, but it means monitoring and clients must inspect response bodies. The GraphQL over HTTP specification work clarifies status-code usage, but in practice you should check how your chosen server library behaves.
Most modern apps are a front end talking to many APIs at once.
Security considerations
- Authorisation must be enforced at the resolver or data layer in GraphQL, because one query can reach many types. In REST, per-endpoint checks are easier to reason about.
- Introspection lets clients discover the full schema. Useful in development; many teams disable or restrict it in production for non-public APIs.
- Denial of service through expensive queries is a GraphQL-specific risk; use depth and complexity limits, timeouts and rate limiting by query cost.
- Both need input validation, authentication, TLS and rate limiting. The OWASP API Security Top 10 applies to both.
Comparison table
| Aspect | REST | GraphQL |
|---|---|---|
| Endpoints | Many, resource-based | Typically one |
| Response shape | Defined by server | Defined by client query |
| Over- and under-fetching | Common without extra conventions | Largely avoided |
| Round-trips for complex screens | Often several | Usually one |
| HTTP caching | Native (CDN, browser, ETag) | Requires persisted queries or app-level caching |
| Error signalling | HTTP status codes | errors array, often with HTTP 200 |
| Versioning | URL or header versions | Schema evolution with deprecation |
| Typing and introspection | Via OpenAPI (optional) | Built-in, strongly typed schema |
| Performance pitfalls | Chatty clients, large payloads | N+1 resolvers, expensive nested queries |
| File uploads | Straightforward (multipart) | Not in core spec; usually handled via separate REST endpoint or extensions |
| Tooling maturity | Universal | Mature in JavaScript/TypeScript ecosystems, good elsewhere |
| Learning curve | Low | Moderate |
| Best fit | Public and partner APIs, CRUD services, webhooks, payment integrations | Complex UIs, mobile apps, aggregating many backends |
Which should East African teams choose?
Practical factors in the region shift the balance in specific ways:
- Mobile-first users on variable networks. Fewer round-trips and smaller payloads help users on congested LTE or 3G and those watching data bundles. That favours GraphQL for app backends, though a well-designed REST API with compression, field selection and composite endpoints can perform comparably.
- Partner and payment integrations. M-Pesa Daraja, bank APIs, KRA eTIMS and most third-party services in the region are REST or REST-like. Your integration layer will speak REST regardless.
- Skills. REST skills are widespread across Kenyan developer communities. GraphQL expertise exists but is less common, particularly for server-side performance tuning and security.
- Infrastructure costs. CDN caching of REST responses can significantly reduce origin load and egress, which matters when hosting in hyperscaler regions billed in USD.
Decision checklist
- Are the consumers external partners you do not control? Prefer REST.
- Do several client apps need different views of the same rich, related data? Consider GraphQL.
- Is most of your data public and cacheable? REST with a CDN is simple and cheap.
- Do you aggregate many internal services or databases into one client-facing API? GraphQL as a gateway works well.
- Does your team have capacity to manage query cost limits, DataLoader batching and resolver-level authorisation? If not, start with REST.
A common and sensible architecture uses both: REST for public APIs, webhooks and integrations, and GraphQL as a backend-for-frontend for your own web and mobile apps.
Common mistakes
- Adopting GraphQL for a simple CRUD API and paying the complexity cost without the benefit.
- Skipping DataLoader batching, then discovering database overload in production.
- Leaving introspection and unlimited query depth open on a private production API.
- Ignoring HTTP caching in REST, missing an easy performance win.
- Breaking REST clients by changing response shapes without a new version.
- Assuming GraphQL fixes poor data modelling. It exposes your domain model; a messy model becomes a messy schema.
FAQ
Is GraphQL faster than REST?
Not inherently. GraphQL can reduce round-trips and payload size for complex screens, while REST can be faster for simple, cacheable requests. Performance depends on implementation, caching and database access patterns.
Can I use REST and GraphQL together?
Yes. Many organisations expose REST for partners and webhooks while using GraphQL internally for their own front ends. Both can share the same services and databases.
Does GraphQL replace REST?
No. GraphQL addresses specific problems around flexible data fetching. REST remains the dominant style for public APIs and third-party integrations.
How does versioning work in GraphQL?
Instead of new URL versions, you add fields and deprecate old ones within a single schema, monitoring field usage before removal.
For practical guidance on connecting your application to payment providers and other external services, read How to Integrate Third-Party APIs Into Web Applications.
How TechBytes can help
We help teams choose and implement the right API style for each use case, from REST integrations with M-Pesa and eTIMS to GraphQL backends for mobile apps. Our engineers can review existing APIs for performance issues such as N+1 queries, design caching strategies, and harden APIs against OWASP risks. Explore our software development services or our cybersecurity services for API security reviews.


