
Almost every modern application depends on APIs. When a shop's checkout triggers an M-Pesa STK push, when a mobile app loads your account balance, or when an ERP sends invoice data to KRA's eTIMS, systems are exchanging structured messages over HTTP, and most of those exchanges follow REST conventions. This guide explains what a REST API is, how HTTP methods, status codes and JSON fit together, what idempotency means and why it matters for payments, and how to call and design REST APIs with confidence.
Key takeaways
- A REST API exposes resources (customers, orders, payments) at URLs and lets clients act on them using standard HTTP methods.
- Status codes tell the client what happened; using them correctly makes integrations far easier to build and debug.
- Idempotency means repeating a request has the same effect as sending it once. It is essential on unreliable networks where clients retry.
- JSON is the dominant data format; consistent field naming, dates and money representation prevent integration bugs.
- You can explore any REST API with
curlbefore writing a line of application code.
What "REST" means
REST stands for Representational State Transfer, an architectural style described by Roy Fielding in his 2000 doctoral dissertation. In everyday usage, a "REST API" is an HTTP API that follows a set of conventions:
- Resources identified by URLs.
/customers/42is customer 42;/customers/42/ordersis that customer's orders. - Standard methods. Clients use HTTP verbs (GET, POST, PUT, PATCH, DELETE) rather than inventing operations such as
getCustomerById. - Representations. The server returns a representation of the resource, usually JSON.
- Statelessness. Each request carries everything needed to process it, including authentication. The server does not rely on remembering previous requests from the same client. This makes horizontal scaling and load balancing straightforward.
- Cacheability. Responses state whether and for how long they can be cached.
- Uniform interface. The same patterns apply across all resources, so once you understand one endpoint you can predict the others.
In practice, many APIs described as REST are not strictly faithful to every constraint in Fielding's definition. That is fine. What matters for most teams is a predictable, well-documented HTTP interface.
Readable, typed code is what keeps a front end maintainable as the team grows.
Anatomy of a request and response
A REST call is an HTTP request with four parts:
POST /v1/orders HTTP/1.1
Host: api.example.co.ke
Authorization: Bearer eyJhbGciOi...
Content-Type: application/json
Idempotency-Key: 9f1c2b7e-3d4a-4c1e-9b2f-1a2b3c4d5e6f
{
"customer_id": 42,
"items": [
{ "sku": "MAIZE-2KG", "quantity": 3 }
],
"currency": "KES"
}
- Method and path:
POST /v1/orders, meaning "create a new order". - Headers: metadata, including authentication and content type.
- Body: the data, typically JSON. GET requests normally have no body.
The response:
HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/orders/10045
{
"id": 10045,
"customer_id": 42,
"status": "pending_payment",
"total": { "amount": "450.00", "currency": "KES" },
"created_at": "2026-11-26T09:15:00+03:00"
}
The status code (201 Created), headers (Location points to the new resource) and body together tell the client exactly what happened.
HTTP methods
| Method | Purpose | Example | Safe | Idempotent |
|---|---|---|---|---|
| GET | Retrieve a resource or collection | GET /orders/10045 | Yes | Yes |
| POST | Create a resource or trigger an action | POST /orders | No | No |
| PUT | Replace a resource entirely | PUT /customers/42 | No | Yes |
| PATCH | Partially update a resource | PATCH /customers/42 | No | Not guaranteed |
| DELETE | Remove a resource | DELETE /orders/10045 | No | Yes |
| HEAD | Like GET but headers only | HEAD /files/report.pdf | Yes | Yes |
| OPTIONS | Discover allowed methods; used in CORS preflight | OPTIONS /orders | Yes | Yes |
Safe means the request should not change server state. Idempotent means making the same request several times has the same effect on the server as making it once. These definitions come from the HTTP specification (RFC 9110).
Status codes
Status codes are grouped by their first digit: 2xx success, 3xx redirection, 4xx client errors, 5xx server errors.
| Code | Name | When to use it |
|---|---|---|
| 200 | OK | Successful GET, PUT or PATCH returning a body |
| 201 | Created | Resource created; include a Location header |
| 202 | Accepted | Request accepted for asynchronous processing (common with payment initiation) |
| 204 | No Content | Success with no body, often for DELETE |
| 301 / 308 | Moved Permanently / Permanent Redirect | Resource has a new URL |
| 304 | Not Modified | Cached version is still valid |
| 400 | Bad Request | Malformed request or invalid JSON |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Authenticated but not allowed |
| 404 | Not Found | Resource does not exist |
| 409 | Conflict | State conflict, such as a duplicate or version mismatch |
| 422 | Unprocessable Content | Well-formed but semantically invalid (failed validation) |
| 429 | Too Many Requests | Rate limit exceeded; check Retry-After |
| 500 | Internal Server Error | Unexpected server failure |
| 502 / 503 / 504 | Bad Gateway / Service Unavailable / Gateway Timeout | Upstream or availability problems; usually safe to retry with backoff |
A common anti-pattern is returning 200 OK with {"success": false} in the body. It forces every client to parse bodies to detect errors and breaks monitoring tools that count error codes. Some widely used APIs do this, so you will need to handle it as a consumer, but avoid it in APIs you design.
Idempotency and why it matters in East Africa
Networks fail. A request from a rider's phone on a congested LTE cell, or from a server whose fibre link flaps, may reach the server and be processed, but the response never arrives. The client cannot tell whether the request succeeded, so it retries.
For a GET, that is harmless. For a payment, it is dangerous: a naive retry of POST /payments could charge the customer twice.
There are two main defences:
- Use idempotent methods where possible.
PUT /customers/42with the full customer record can be repeated safely. - Use idempotency keys for POST. The client generates a unique key (for example, a UUID) per logical operation and sends it in a header such as
Idempotency-Key. The server stores the key with the result; if it sees the same key again, it returns the stored result rather than processing again. This pattern is used by several major payment APIs and is being standardised in an IETF draft.
Server-side, combine idempotency keys with database constraints. For example, store the M-Pesa receipt number as a unique column, so a re-delivered callback cannot create a duplicate payment record.
Working with JSON
JSON (JavaScript Object Notation) is the standard payload format for REST APIs. A few conventions save a lot of pain:
- Consistent casing. Pick
snake_caseorcamelCaseand use it everywhere. - Dates in ISO 8601 with time zone.
2026-11-26T09:15:00+03:00, not26/11/2026. East Africa Time is UTC+3 with no daylight saving. - Money as strings or integer minor units.
"450.00"or45000(cents), with an explicit currency. Floating-point numbers introduce rounding errors. - Phone numbers in a consistent format. For Kenya, international format such as
2547XXXXXXXX(as M-Pesa APIs use) avoids ambiguity between07...,+254...and254.... - Explicit nulls versus missing fields. Document whether a missing field means "unchanged" (useful for PATCH) or "null".
- Structured errors. A consistent error shape helps clients. RFC 9457 (Problem Details for HTTP APIs) defines a standard format:
{
"type": "https://api.example.co.ke/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"detail": "Only 2 units of MAIZE-2KG remain at the Thika branch.",
"instance": "/v1/orders"
}
Most modern apps are a front end talking to many APIs at once.
Exploring an API with curl
curl is installed on Linux, macOS and current versions of Windows. It is the fastest way to understand an API.
Retrieve a resource and show response headers:
curl -i https://api.example.co.ke/v1/orders/10045 \
-H "Authorization: Bearer $API_TOKEN"
Create a resource with a JSON body and an idempotency key:
curl -X POST https://api.example.co.ke/v1/orders \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{"customer_id": 42, "items": [{"sku": "MAIZE-2KG", "quantity": 3}], "currency": "KES"}'
Partially update a resource:
curl -X PATCH https://api.example.co.ke/v1/customers/42 \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"phone": "254712345678"}'
Filter and paginate a collection using query parameters:
curl "https://api.example.co.ke/v1/orders?status=paid&created_after=2026-11-01&limit=50&cursor=abc123" \
-H "Authorization: Bearer $API_TOKEN"
Real-world example: Safaricom's Daraja API uses OAuth client credentials. You exchange your consumer key and secret for an access token, then call other endpoints with it. The sandbox token request looks like this (see the official Daraja documentation for current endpoints):
curl -u "$CONSUMER_KEY:$CONSUMER_SECRET" \
"https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
Keep credentials in environment variables, as above, rather than pasting them into commands that end up in shell history or shared documentation.
Designing a simple REST API: step by step
- Identify resources as nouns:
customers,orders,payments,branches. - Define URLs as plural collections with IDs:
/orders,/orders/{id}, and nested only where the relationship is strong (/orders/{id}/items). - Map operations to methods. Avoid verbs in URLs except for genuine actions that do not fit CRUD, such as
POST /orders/{id}/cancel. - Specify request and response schemas using OpenAPI, so documentation and client code can be generated.
- Choose status codes for each outcome, including errors.
- Add pagination for collections. Cursor-based pagination is more robust than page numbers for frequently changing data.
- Version the API, typically with a prefix such as
/v1, so breaking changes do not surprise existing clients. - Secure it: HTTPS only, token-based authentication, authorisation checks on every resource, input validation and rate limiting. The OWASP API Security Top 10 is the standard checklist.
- Document and test with examples that a developer can copy and run.
Performance on regional networks
Many users in East Africa connect via mobile data with variable latency and costly bundles. API design affects their experience directly:
- Support compression (gzip or Brotli) for JSON responses.
- Paginate and allow field selection so mobile clients download only what they need.
- Use caching headers (
ETag,Cache-Control) so unchanged data is not re-downloaded. - Host APIs close to users. Round-trips from Nairobi to European regions are noticeably slower than to local data centres or South African regions; measure from real user networks.
- Design for retries with idempotency, as discussed above.
Common mistakes
- Verbs in URLs such as
/getOrdersor/createCustomer. Let HTTP methods carry the action. - Returning 200 for errors, which hides failures from clients and monitoring.
- Non-idempotent payment endpoints without idempotency keys, leading to duplicate charges on retries.
- Floating-point money in JSON.
- Leaking internal details such as stack traces or database errors in responses.
- No pagination, causing huge responses that time out on mobile networks.
- Credentials in URLs or query strings, where they end up in logs.
FAQ
What is the difference between an API and a REST API?
An API is any defined interface for software to communicate. A REST API is a specific style of web API that uses HTTP methods, URLs for resources and stateless requests, typically exchanging JSON.
Is REST the same as HTTP?
No. HTTP is the protocol; REST is an architectural style that uses HTTP's features (methods, status codes, headers, caching) in a consistent way.
What does idempotent mean in a REST API?
An idempotent request produces the same server state whether it is sent once or many times. GET, PUT and DELETE are idempotent by definition; POST is not, which is why payment APIs use idempotency keys.
Should I use REST or GraphQL?
REST is simpler, well understood and works well with HTTP caching. GraphQL helps when clients need flexible, nested data from many sources. See REST API vs GraphQL: Understanding the Differences for a detailed comparison.
How do I start integrating a third-party REST API?
Read the documentation, get sandbox credentials, explore endpoints with curl, then implement authentication, retries and error handling in your application. Our guide on integrating third-party APIs into web applications covers this in depth.
How TechBytes can help
We design, build and secure REST APIs for East African businesses, from M-Pesa and eTIMS integrations to internal platforms connecting ERPs, POS systems and mobile apps. Our engineers can review an existing API against OWASP guidance, document it with OpenAPI, or build new services with retries, idempotency and monitoring designed in. Explore our software development services or contact us to discuss your project.


