API Fundamentals: Architectures, Authentication, REST Design and Security
How applications talk to each other, how an API knows who is calling, how to design endpoints other developers can read at a glance, and how to keep all of it safe.
Introduction
Every modern application is a set of systems talking to each other through APIs. A mobile app asks a server for your orders, a payment service tells inventory to drop stock, a dashboard streams live prices.
Building an API that works is the easy part. Building one that other developers understand, that scales, and that does not leak data takes deliberate decisions in four areas:
- Architecture: how systems exchange data (REST, GraphQL, SOAP, gRPC, WebSocket, event-driven)
- Authentication: how an API knows who is calling (API keys, Basic Auth, JWT, OAuth 2.0)
- REST design: URLs, HTTP methods, status codes, pagination, errors and versioning
- Security: HTTPS, CORS, rate limiting, input validation and secrets
Each section stands on its own. If you are preparing for backend interviews, read it top to bottom.
The Six Common API Architectures
API architecture defines how applications exchange data. The choice affects how the system scales, how fast clients get data, how easily the API changes, and how pleasant it is to use. Each of these six solves a different problem.
1. REST (Representational State Transfer)
REST, the most widely used style, treats everything as a resource with its own URL and uses HTTP methods (GET, POST, PUT, PATCH, DELETE) to act on it. It is stateless: each request carries everything the server needs, and the server keeps no client session between requests. Most modern REST APIs return JSON.
GET /users/15 HTTP/1.1
Host: api.example.com
{
"id": 15,
"name": "Riyas"
}
Best for: web and mobile apps, public APIs and CRUD operations.
2. GraphQL
GraphQL fixes two REST problems: over-fetching (the endpoint returns more than the screen needs) and under-fetching (the screen needs /users, /orders and /products, so the client makes three requests). It exposes a single endpoint, usually /graphql, where the client describes the exact shape of data it wants.
{
user(id: 15) {
id
name
email
orders {
id
total
}
}
}
{
"data": {
"user": {
"id": 15,
"name": "Riyas",
"email": "riyas@example.com",
"orders": [
{ "id": 101, "total": 2500 }
]
}
}
}
One request replaced two or three REST calls, and the typed, self-documenting schema gives GraphQL excellent tooling.
Best for: complex frontends, mobile apps on slow networks, and gateways that aggregate backend services.
Watch out for: HTTP caching is harder because everything goes through one URL with POST, and a careless query can request a huge nested graph. Limit query depth and cost on the server.
3. SOAP (Simple Object Access Protocol)
SOAP is an XML-based protocol with a strict specification. It predates REST and remains common in banking, healthcare, government and telecom.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<AuthToken>abc123</AuthToken>
</soap:Header>
<soap:Body>
<GetUserRequest>
<UserID>15</UserID>
</GetUserRequest>
</soap:Body>
</soap:Envelope>
It offers strict contracts defined in a WSDL file, message-level signing and encryption through WS-Security, and extensions for reliable messaging and distributed transactions. The cost is verbosity: heavy XML, older tooling and slower development.
Best for: enterprise and regulated systems where formal contracts and compliance matter more than development speed. Few new public APIs choose SOAP, but you will integrate with it.
4. gRPC
gRPC is a high-performance RPC framework from Google. It serialises data with Protocol Buffers, a compact binary format, over HTTP/2. You define the contract in a .proto file and generate client and server code:
syntax = "proto3";
service UserService {
rpc GetUser (UserRequest) returns (UserResponse);
rpc CreateUser (CreateUserRequest) returns (UserResponse);
}
message UserRequest {
int32 id = 1;
}
message UserResponse {
int32 id = 1;
string name = 2;
string email = 3;
}
Binary payloads are smaller and faster to parse than JSON, the .proto file is the single source of truth for types, and client, server and bi-directional streaming are built in.
Best for: service-to-service calls, high-throughput internal APIs and real-time pipelines.
Watch out for: browsers cannot call gRPC directly. You need gRPC-Web and a proxy, which is why most teams keep gRPC internal and put REST or GraphQL in front of web clients.
5. WebSocket
REST is request and response. A WebSocket opens a persistent, two-way connection; once open, either side can send a message at any time, so the server can push instead of the client polling.
Client Server │ 1. HTTP request with Upgrade header │ │ ────────────────────────────────────▶ │ │ 101 Switching Protocols │ │ ◀──────────────────────────────────── │ │ │ │ 2. Connection stays open │ │ ◀──────── messages both ways ───────▶ │ │ │ │ 3. Either side closes │
const socket = new WebSocket("wss://example.com/socket");
socket.onopen = () => console.log("Connection opened");
socket.onmessage = (event) => console.log("Message:", event.data);
socket.onclose = () => console.log("Connection closed");
Best for: chat, live dashboards, multiplayer games, stock tickers and notifications.
Watch out for: long-lived connections are stateful. Load balancing, reconnection and scaling across servers need more thought than stateless REST.
6. Event-Driven APIs
Services do not call each other directly. A service publishes an event when something happens, and interested services react. For an e-commerce order:
- The order service publishes
OrderCreated. - The payment service charges the card and publishes
PaymentSucceeded. - Inventory reduces stock, email sends a confirmation, and shipping starts delivery.
The order service knows nothing about email or shipping. A new consumer, say a loyalty-points service, plugs in without touching existing code.
{
"event": "OrderCreated",
"event_id": "evt_9867ab",
"timestamp": "2026-10-07T10:30:45Z",
"data": {
"order_id": 10123,
"customer_id": 501,
"total": 2500.00,
"currency": "INR"
},
"source": "order-service"
}
Events travel through a broker such as Kafka, RabbitMQ or AWS EventBridge. You get loose coupling, scaling by adding consumers, fast user-facing requests, and events that can be retried or replayed.
Watch out for: more moving parts, harder debugging across services, and eventual consistency. The email might go out a second after the order is saved.
Which Architecture Should You Choose?
There is no single best architecture. Pick based on the application, performance needs, data shape, real-time requirements and what your team knows.
| Architecture | Best for | Strengths | Trade-offs |
|---|---|---|---|
| REST | General web and mobile apps, public APIs | Simple, widely adopted, cacheable, great tooling | Over-fetching; many calls for complex screens |
| GraphQL | Complex frontends, API aggregation | Fetch exactly what you need; one endpoint; typed schema | Caching is harder; overkill for simple apps |
| SOAP | Enterprise and regulated systems | Strict contracts, WS-Security, transaction support | Heavy XML; slower development |
| gRPC | Internal microservices | Very fast, compact, strongly typed, streaming | Not browser-friendly; steeper learning curve |
| WebSocket | Real-time apps | Two-way, low latency, persistent | Stateful connections are harder to scale |
| Event-driven | Distributed, asynchronous systems | Loose coupling, scalable, resilient | Complex setup; harder to debug; eventual consistency |
Real systems mix them: REST or GraphQL for web and mobile clients, gRPC between internal services, and an event bus for background work.
Web / Mobile ──▶ REST API ──▶ Event Bus (Kafka / RabbitMQ) ──▶ Microservices
│
gRPC between services
Authentication vs Authorization
A bank teller checks your ID before showing your balance. APIs work the same way, and two separate questions often get mixed up:
| Authentication | Authorization | |
|---|---|---|
| Question | Who are you? | What are you allowed to do? |
| Checks | Identity | Permissions |
| Example | Logging into Gmail with your password | A manager can view salaries; an intern cannot |
| Failure status | 401 Unauthorized | 403 Forbidden |
Authentication always comes first: you cannot decide what someone may do until you know who they are.
Four Common Authentication Methods
1. API Key
The client sends a unique key with every request, usually in a header, and the server allows the request if the key is valid:
GET /weather HTTP/1.1
Host: api.weatherapp.com
x-api-key: abc123xyz
API keys are easy to issue and light to check, which suits server-to-server calls and simple public APIs. But a key identifies an application, not a user, and anyone who sees it can use it until you revoke it. It is not enough on its own for sensitive data. Never put a key in frontend code or a URL query string, where browsers, logs and proxies record it.
2. Basic Authentication
The client sends a username and password with every request, joined with a colon and Base64-encoded:
GET /users/15 HTTP/1.1
Host: api.example.com
Authorization: Basic cml5YXM6cGFzc3dvcmQ=
That header decodes to riyas:password. Base64 is encoding, not encryption, so Basic Auth is only acceptable over HTTPS. It is trivial to implement and universally supported, which makes it fine for internal tools. Real credentials travel on every request and never expire, so avoid it for public APIs and sensitive data.
3. Bearer Token (JWT)
Like a visitor pass: security checks your ID once, then you show the pass all day.
- The client sends a username and password once.
- The server verifies them and returns a signed JWT.
- The client sends the token on every request.
- The server checks the signature and serves the data.
GET /api/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
A JWT has three dot-separated parts: a header, a payload of claims (user ID, roles, expiry) and a signature. Because the signature proves the claims were not altered, the server can trust them without a session store or database lookup, and any tampering breaks the signature.
Rules that keep JWTs safe:
- The payload is signed, not encrypted. Anyone can decode it, so never put secrets in it.
- Keep access tokens short-lived (minutes, not days) and use refresh tokens for new ones. Revoking a JWT early needs extra work such as a deny-list; short expiry limits the damage.
- Store tokens in HttpOnly cookies or secure platform storage, not
localStorage, where any injected script can read them. - Always use HTTPS.
4. OAuth 2.0
“Continue with Google” is OAuth 2.0:
- You click “Continue with Google” and the app redirects you to Google.
- Google verifies you and asks whether to grant the app access to your profile.
- Google sends the app an access token.
- The app uses the token to call Google’s APIs on your behalf.
The app never sees your password. It gets a token with the limited access you approved, which you can revoke later.
Strictly, OAuth 2.0 is an authorization framework. The “sign in with” part comes from OpenID Connect, a thin identity layer on top; in practice they arrive together. Common uses are social login, apps calling third-party APIs for a user, enterprise single sign-on and mobile apps.
OAuth is easy to get subtly wrong. Use a well-maintained library, validate the state parameter, use PKCE for mobile and single-page apps, and register exact redirect URIs.
Which Authentication Should You Use?
| Method | Best for | How it works | Security | Ease of use |
|---|---|---|---|---|
| API key | Server-to-server, simple public APIs | Client sends a unique key on each request | Medium | Very easy |
| Basic Auth | Internal tools, low-risk apps | Base64 username and password on each request | Low | Easy |
| JWT | Web and mobile apps, SPAs, microservices | Signed token verified without a session store | High | Moderate |
| OAuth 2.0 | Third-party login, delegated access | User signs in with a provider; app gets a scoped token | Very high | Moderate |
Consider who calls the API, how sensitive the data is, where it is consumed, and whether you need a user’s identity or only an application’s. Then pick the simplest method that keeps the data safe. Methods combine well: a common pattern is OAuth 2.0 for login, after which your backend issues a short-lived JWT for API access.
REST API Design Best Practices
A good API is consistent and predictable, so developers can guess an endpoint before reading the docs. That comes from a handful of conventions applied everywhere. Every call is a request (method, URL, headers, optional body) and a response (status code, headers, body):
GET /api/users/15 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 15,
"name": "Riyas AC",
"email": "riyas@example.com",
"role": "Developer",
"status": "Active"
}
Use Nouns, Not Verbs
URLs name resources; HTTP methods name actions.
| Avoid | Use |
|---|---|
GET /getUsers | GET /users |
POST /createUser | POST /users |
POST /updateUser | PUT /users/15 or PATCH /users/15 |
POST /deleteUser | DELETE /users/15 |
Keep URLs Consistent
Use lowercase, plural nouns (/users, /orders), hyphens between words (/order-items), and short paths that nest only for real ownership (/users/15/orders). Apply the same pattern everywhere. Avoid mixes like /get_user, /userList and /ProductData.
Use the Right HTTP Method
| Method | CRUD | Example | Idempotent | Safe |
|---|---|---|---|---|
GET | Read | GET /users/15 | Yes | Yes |
POST | Create | POST /users | No | No |
PUT | Replace | PUT /users/15 | Yes | No |
PATCH | Partial update | PATCH /users/15 | Depends | No |
DELETE | Delete | DELETE /users/15 | Yes | No |
Safe means the request does not change server data. Idempotent means sending it many times has the same effect as once, which matters for retries: a client can safely retry a timed-out PUT, but retrying a POST may create a duplicate. PATCH depends on the payload: {"price": 499} is idempotent; {"stock": "+1"} is not. Do not use POST for everything; the method tells clients, caches and proxies how to treat the request.
Return Meaningful Status Codes
Never return 200 OK with {"error": "not found"} in the body. The status code is the first thing a client checks.
| Range | Meaning | Common codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved Permanently, 304 Not Modified |
| 4xx | Client error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
| 5xx | Server error | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable |
Use the most specific code that fits, use it the same way across the API, and document every code an endpoint can return.
Support Filtering and Pagination
A /products endpoint backed by 10,000 rows should never return all of them. Let clients ask for what they need with query parameters for page, limit, filters and sorting:
GET /products?page=1&limit=10 GET /products?category=electronics GET /products?sort=price&order=desc GET /products?category=books&sort=name
Return pagination metadata and navigation links so clients do not build URLs themselves:
{
"data": [
{ "id": 1, "name": "Product 1", "price": 120 },
{ "id": 2, "name": "Product 2", "price": 150 }
],
"meta": {
"page": 1,
"limit": 2,
"total": 45,
"total_pages": 23
},
"links": {
"next": "/products?page=2&limit=2",
"prev": null
}
}
- Set a sensible default limit (10 or 20) when the client sends none
- Enforce a maximum so
?limit=100000cannot load the whole table - For large or fast-changing data, prefer cursor pagination (
?after=evt_9867ab) over page numbers; offsets get slow and skip rows when data shifts
Make Error Messages Helpful
{ "error": "Something went wrong" } tells the developer nothing. A good error says what failed, which field, and how to fix it:
{
"status": 400,
"error": "Validation Failed",
"code": "VALIDATION_ERROR",
"message": "One or more fields are invalid.",
"details": [
{ "field": "email", "issue": "Invalid email format" },
{ "field": "password", "issue": "Password is too short" }
],
"timestamp": "2026-10-07T10:30:45Z"
}
The machine-readable code lets clients branch on the error, details lists field-level problems, and timestamp helps match logs.
- Use one error format across the whole API
- Make messages specific and actionable
- Log stack traces and internals on the server, never in the response
- Never expose sensitive data, such as whether an email exists on a login form
Version Your APIs
Versioning lets you improve an API without breaking clients that depend on the old behaviour:
GET /api/v1/users → { id, name, email }
GET /api/v2/users → { id, name, email, phone, created_at }
Version 1 keeps working while new clients move to version 2. Never change the behaviour of a published version; release a new one.
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URI path | /api/v1/users | Clear, widely adopted, easy to test | Longer URLs |
| Query parameter | /api/users?version=1 | Simple to add | Easy for clients to forget |
| Header | API-Version: 1 | Clean URLs | Harder to test in a browser |
Release a new version when you remove or rename a field, change a field’s type or meaning, change visible business logic, or make a security change old clients cannot follow. Adding an optional field is not a breaking change. When you do release one, document it, publish a migration guide, announce deprecation dates, and keep the old version running long enough for clients to move.
API Security Essentials
Every API on the internet is a target. Without proper security, attackers can steal data, take over accounts, abuse endpoints and take the application down.
Always Use HTTPS
HTTP sends plain text that anyone on the network path can read or modify; HTTPS encrypts it with TLS. Serve every endpoint over HTTPS, internal ones too where possible, redirect or reject plain HTTP, and send Strict-Transport-Security so browsers never downgrade.
Configure CORS Carefully
CORS (Cross-Origin Resource Sharing) controls which websites may call your API from a browser.
Allowed: Access-Control-Allow-Origin: https://yourapp.com Avoid: Access-Control-Allow-Origin: *
Allow only trusted domains, never use * for APIs that handle sensitive data or cookies, and review the list when frontends change. CORS is enforced by browsers, so it does not stop curl, scripts or other servers. It protects your users’ browsers from malicious sites; authentication protects your API.
Apply Rate Limiting
Rate limiting caps how many requests a client can make in a time window, for example 100 requests per minute per user, 1,000 per hour per API key, or 10 login attempts per minute per IP or account. Over the limit, return 429 with a Retry-After header so well-behaved clients know when to retry:
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Limits prevent abuse, slow brute-force attacks and keep the API available. Gateways such as Nginx, Kong or AWS API Gateway can enforce them before requests reach your code.
Validate Every Input
Never trust client input. Validate on the server even if the frontend already did; frontend validation is for user experience, and anyone can bypass it with a direct HTTP call.
{
"email": "user@@example",
"id": "abc123",
"amount": "-1000",
"role": "admin"
}
Reject every field above: the email is malformed, the ID has the wrong type, the amount is negative, and role should never be accepted from the client. Use parameterised queries or your ORM so input never becomes part of a SQL or NoSQL query.
Protect Your Secrets
API keys, database passwords, tokens and private keys stay out of source code:
# Bad: hardcoded in source
SECRET_KEY = "my-secret-key"
DB_PASSWORD = "password123"
# Better: read from the environment
import os
SECRET_KEY = os.getenv("SECRET_KEY")
DB_PASSWORD = os.getenv("DB_PASSWORD")
Use environment variables for most applications, secret managers such as AWS Secrets Manager or HashiCorp Vault, CI/CD secret stores for pipelines, and KMS services for encryption keys. Keep local values in a .env file listed in .gitignore. If a secret reaches a repository, rotate it immediately; deleting the commit is not enough.
Common API Security Mistakes
- Secrets in frontend code, URLs or public repos. Anyone can open dev tools, and bots scan GitHub for leaked keys within minutes.
- Weak or missing authentication on endpoints assumed to be “internal”.
- Missing authorization checks. Verify the user may access this record, not only that they are logged in. Changing
/orders/101to/orders/102must not show someone else’s order. - Long-lived or over-permissive tokens. Expire tokens and grant only the scopes the client needs.
- Tokens in
localStorage. One XSS bug exposes every session. - Returning sensitive data such as password hashes, tokens or internal fields.
- Disabling HTTPS, even “just for testing”.
- Trusting client input, overly permissive CORS with
*, and no rate limiting.
Missing authorization checks cause many real incidents; the OWASP API Security Top 10 lists broken object-level authorization first.
Security Checklist Before You Deploy
- HTTPS enabled
- Authentication implemented
- Authorization verified on every endpoint and every record
- Input validated on the server
- Rate limiting configured
- Secrets stored outside the code
- CORS restricted to trusted origins
- Tokens short-lived, with refresh tokens
- Logging and monitoring for suspicious activity
- Dependencies up to date
Security is not a one-time setup. Run this list again whenever the API changes.
Conclusion
A good API comes down to four decisions: REST by default with other architectures where the problem calls for them, the simplest authentication that protects the data, consistent REST conventions, and security on every endpoint and record.