EDUCATION · API · STANDARDS

🔌 API Guide - Design, security and infrastructure

Six sections on Application Interfaces (API) according to international practice: REST principles (Roy Fielding, 2000), HTTP methods and status codes (RFC 9110), security (OWASP API Top 10, OAuth 2.0, JWT), API gateways, reverse proxy and load balancer differences, design practices (RFC 9457, OpenAPI 3.1) and standards references. Examples are illustrative and for learning purposes.

What API is

REST architecture style - Roy Fielding (2000)

API (Application Programming Interface) is a formally defined interface agreement between two software components, which determines how they exchange data. Web API is usually based on the HTTP protocol and REST architecture style: resources are addressed by URL, activities are expressed by HTTP methods, but data are most often transmitted in JSON format.

HTTP pieprasījuma un atbildes cikls Klients nosūta HTTP pieprasījumu ar metodi, ceļu un galvenēm. API serveris atbild ar statusa kodu un JSON saturu. HTTP pieprasījuma un atbildes cikls KLIENTS pārlūks · lietotne cits serviss API SERVERIS resursi pa URL JSON atbilde → GET /v1/lietotaji/42 Accept: application/json · Authorization: Bearer <token> ← 200 OK · Content-Type: application/json { "id": 42, "vards": "Anna", "loma": "klients" } Bezstāvokļa (stateless): katrs pieprasījums satur visu nepieciešamo - serveris neglabā sesijas kontekstu starp izsaukumiem
1
Customer Server

The interface separates the client (exposure layer) from the server (data storage and logic), allowing them to be developed and scaled independently.

2
Free

Each request shall contain all the context necessary for its execution. The server does not maintain the position of the client session, which simplifies horizontal scaling.

3
Capacity

Responses are clearly marked as cache-Control (ETag), reducing server load and response delay.

4
Uniform interface

Common principles of interaction: identification of resources, representation thereof (e.g. JSON), self-practical reports and hyperlinks (HATEOAS).

5
Sounded system

There may be intermediate layers (reverse proxy, gateway, cache) between the client and the server without the customer knowing about them.

6
Code on request

Optional principle: the server can send an executable code (e.g. JavaScript), temporarily expanding the client's functionality.

REST

Resource-oriented architectural style above HTTP. Simple and quashable. Dominates public web API.

GraphQL

One endpoint. The client requires the necessary fields. Reduces excessive and insufficient data loading.

gRPC

Binary, high performance RPC frame (Protocol Buffers, HTTP/2). Suitable for internal microservice communication.

WebSocket / SOAP

WebSocket - a permanent two-way real-time channel. SOAP - older XML protocol with a strictly defined contract (WSDL).

RFC 9110 - HTTP Semantics

Methods (safe/idempotent) and status codes

Method Safe Idempotent Chechoyam Typical application
GETRead resource without side effects
HEADReturns only headers without body
POSTrareCreates a resource or launches an activity
JUFully replaces the resource
PAATCHPartially update resource
DELETEDeleting Resource
OPTIONSMethods supported. CORS preview
HTTP statusa kodu saimes Piecas statusa kodu saimes: 1xx informatīvs, 2xx veiksme, 3xx pāradresācija, 4xx klienta kļūda, 5xx servera kļūda. HTTP statusa kodu saimes (RFC 9110) 1xx · Informatīvs 100 Continue 101 Switching 2xx · Veiksme 200 OK 201 Created 202 Accepted 204 No Content 3xx · Pāradresācija 301 Moved Perm. 302 Found 304 Not Modified 307 Temp. Redirect 4xx · Klienta kļūda 400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found 409 Conflict 422 Unprocessable 429 Too Many Req. 5xx · Servera kļūda 500 Internal 502 Bad Gateway 503 Unavailable 504 Gateway Timeout Pamatprincips: 4xx norāda uz kļūdu klienta pieprasījumā (laba prakse - atgriezt strukturētus kļūdas datus). 5xx - uz kļūdu servera pusē

Safe

Do not change server status. Just read the data. GET, HEAD, OPTIONS.

Idempotent

The repetition of the same request leads to the same end result as a single call. Essential for safe repeat after a net failure.

POST not idempotent

The repeated POST may create duplicates. Solution - Idempotency-Key header (see section Design Practices).

OWASP API Security Top 10:2023 · OAuth 2.0 · JWT

Authentication, authorisation and most common API risks

API security is based on a clear separation between authentication (identity confirmation) and authorization (defining access rights). On the web, the standard solution is OAuth 2.0 with access tokens (usually JWT), which are checked in each request.

OAuth 2.0 autorizācijas koda plūsma ar PKCE Sešu soļu plūsma starp lietotāju, klienta lietotni, autorizācijas serveri un API resursu serveri. OAuth 2.0 - autorizācijas koda plūsma ar PKCE Lietotājs (RO) Klients (lietotne) Autorizācijas serv. API (resursi) 1 · sākt pieteikšanos 2 · authorization request + PKCE code_challenge 3 · autentifikācija + piekrišana 4 · authorization code 5 · code + code_verifier → access token (JWT) + refresh 6 · GET /resurss + Bearer token → 200 + dati PKCE (RFC 7636) sasaista koda apmaiņu ar sākotnējo pieprasītāju - aizsargā publiskus klientus pret koda pārtveršanu

API keys

Simple service identification. Not to be placed on the customer side or code repository. Regularly change (rotation).

OAuth 2.0 / OIDC

Delegated authorization with tokens. The OIDC adds an identity layer (user authentication).

JWT

Cryptographically signed token in three parts: header.payload.signature. Always check the signature, publisher (issue) and expiry date (exp).

mTLS

Two-sided TLS - both client and server present certificates. Strong mutual authentication between services.

API1
BOLA

Lack of object level authorization - the user accesss an object of another subject by manipulating an identifier (e.g. /recini/123). The most common API risk.

API2
Incomplete authentication

Weak or incorrectly validated token, unverified signature, unlimited number of login attempts.

API3
BOPLA

Lack of authorisation of object properties level - excessive disclosure of data in response or unauthorised mass assignment.

API4
Unlimited consumption of resources

Lack of volume and speed limits - this allows service failure (DoS) and infrastructure costs to increase.

API5
BFLA

Lack of functionality level authorization - the usual user accesses administrative functions.

API6
Sensitive business flows

Unlimited access to sensitive business flows - automated abuse (e.g. mass ticket shopping).

API7
SSRF

Server side requests for counterfeiting - the server executes the request of an attacker controlled URL, reaching internal resources.

API8
Deficiencies in security configuration

Missing safety heads, excessively open CORS, detailed error messages.

API9
Insufficient management of inventories

Forgotten or outdated versions and test media remain publicly available and unsafe.

API10
Insecure consumption

Uncritical trust in third party API data without validation and limitations.

Infrastructure in front of API

API gateway vs reverse proxy vs load balancer

All three are located between the customer and backend, so they tend to be confused. In fact, they are one basic concept - reverse proxy - types that specialize in different functions. In practice, their boundaries overlap and often operate simultaneously.

Tipiska produkcijas plūsma: klienti, slodzes balansētājs, API vārteja, mikroservisi Klienti vēršas pie slodzes balansētāja, tas nodod API vārtejai, kas autentificē un maršrutē uz mikroservisiem. Slodzes balansētājs un vārteja ir reverse proxy slānis. Kur katrs atrodas - tipiska produkcijas plūsma reverse proxy slānis KLIENTI Mobilā lietotne Tīmekļa SPA Partnera serviss Slodzes balansētājs L4 / L7 trafika sadale health checks API vārteja L7 · vienots ieejas punkts auth · rate-limit transformācija agregācija · maršrutēšana MIKROSERVISI Autentifikācija Lietotāji Pasūtījumi Maksājumi Slodzes balansētājs un API vārteja abi ir specializēti reverse proxy. Praksē viens rīks (piem., Nginx vai Envoy) var pildīt vairākas no šīm lomām vienlaikus.
Aspect Reverse proxy Load balance API Gate
Main objective Transfer requests to backend, hide its topology Split traffic by multiple server instances Manages API - single entry point for microservices
OSI layer L7 (may also L4) L4 (transport) or L7 L7 (use)
Route by Host / road IP/port (L4) or content (L7) API path, versions, consumer
TLS termination Yes Yes (L7) Yes
Authentication / Authorisation Basic (possible WAF) No Yes - OAuth / JWT / API keys (main role)
Rate-limit / Quotas Limited No Yes (main role)
Health checks Rare Yes (main role) Common (through balancer)
Transformation / aggregation No No Yes - REST↔gRPC, combining several services
Typical tools Nginx, Apache, HAPRoxy, Envoy HAPRoxy, Nginx, AWS NLB/ALB, F5 Kong, Apigee, AWS API Gateway, Azure APIM, Tyk

Reverse proxy

Basic Concept - a server in front of a client that transfers requests to backend. Provides cover-up of TLS terms, caches, compressions and topology. The other two are its specialization.

Load balance

Reverse proxy that specializes in traffic distribution (round-robin, lower-connections) and accessibility - with health checks and sticky sessions.

API Gate

Reverse proxy, which specializes in API management: authentication, rate-limit, versioning, transformation, aggregation and observation. It usually also includes load balancing.

In practice

Typical order: client → DNS/CDN → load balance → API gateway → microservices. Borders overlap and one tool often performs several roles.

Good practice · RFC 9457 · OpenAPI 3.1

Versioning, limits, errors and description of the contract

Pieprasījuma apstrādes konveijers caur API vārteju Klienta pieprasījums iziet TLS, autentifikāciju, apjoma limitu, validāciju, maršrutēšanu un transformāciju, pirms sasniedz mikroservisu. Pieprasījuma konveijers caur vārteju Klients pieprasījums API vārteja TLSterminācija AuthN/ZJWT pārbaude Rate-limit429 + Retry Validēshēmu Maršrutēpēc ceļa Transformē+ novēro Mikroserviss biznesa loģika
/v1/
Versioning

URL (v1/...), header or media type. The compatibility of existing versions must not be broken - a new version must be added.

page
Pagination

Large lists are divided into pages by offset/limit or cursor method. The maximum leaf size should always be limited.

429
Rate limiting

Speed limitation of requests by reply 429 Too Many Requests and Retry-After header. Protects against overload and abuse.

key
Idempotency-Key

Idempotency-Key header for POST calls prevents duplicates if the request is repeated after a network failure.

9457
Uniform error format

RFC 9457 Problem Details - machine-readable JSON error structure (type, title, status, detail).

OAS
OpenAPI 3.1

Machine-readable API agreement - generates documentation, customer code and validation. A common source of truth for the interface.

Error response - RFC 9457 Problem Details

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 30

{
  "type":   "https://api.piemers.lv/kludas/rate-limit",
  "title":  "Pārāk daudz pieprasījumu",
  "status": 429,
  "detail": "Limits 100 pieprasījumi minūtē ir pārsniegts.",
  "instance": "/v1/lietotaji"
}

References

International standards and specifications

Relationship to the NIS2

Safe development and testing of APIs shall comply with the requirements of Article 21 (2) (e) of the NIS2 (EU 2022/2555) on security in procurement, development and maintenance.

DGPR

Only necessary (data minimisation) should be disclosed in the reply - excessive disclosure of data (OWASP API3) is also a breach of personal data protection.

Reservation

The material is an educational overview, not a full text of standards. Specific implementation should always be considered as an official source.