๐Ÿ”—

REST APIs

๐Ÿง‘โ€๐Ÿณ Cook

Communication between systems

REST APIs allow applications to communicate using HTTP.


HTTP Methods

MethodActionExample
GETGet dataList users
POSTCreate newCreate user
PUTUpdate allUpdate profile
PATCHPartial updateChange email
DELETERemoveDelete user

URL Structure

GET    /api/users          # List all
GET    /api/users/123      # Get one
POST   /api/users          # Create
PUT    /api/users/123      # Update
DELETE /api/users/123      # Delete

Fetch API

// GET
const res = await fetch('/api/users')
const users = await res.json()

// POST
const res = await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ana', email: 'ana@email.com' })
})

// DELETE
await fetch('/api/users/123', { method: 'DELETE' })

Response codes

CodeMeaning
200OK
201Created
400Client error
401Unauthorized
404Not found
500Server error

Common headers

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer your-token',
  'Accept': 'application/json'
}

Error handling

async function fetchData() {
  const res = await fetch('/api/data')

  if (!res.ok) {
    throw new Error(`Error: ${res.status}`)
  }

  return res.json()
}

๐Ÿ” Fintech APIs: Mandatory Security

APIs handling financial data have special security requirements.

Required Security Headers

// Headers that EVERY financial API must include
const securityHeaders = {
  'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
  'X-Content-Type-Options': 'nosniff',
  'X-Frame-Options': 'DENY',
  'X-XSS-Protection': '1; mode=block',
  'X-Request-ID': crypto.randomUUID(), // Traceability
  'Cache-Control': 'no-store', // Don't cache sensitive data
}

Open Banking Authentication

MethodUseWhen
OAuth 2.0 + PKCEMobile appsBank connections
mTLS (mutual TLS)Server-to-serverInterbank APIs
API Keys + HMACWebhooksVerify origin
JWT with rotationSessionsEnd users

Audit Logging

In fintech, "we don't log that" is not an acceptable answer to a regulator.

// Audit middleware
const auditMiddleware = (req, res, next) => {
  const auditLog = {
    requestId: req.headers['x-request-id'] || crypto.randomUUID(),
    timestamp: new Date().toISOString(),
    method: req.method,
    path: req.path,
    userId: req.user?.id,
    ip: req.ip,
    userAgent: req.headers['user-agent'],
  }

  // Log at start
  logger.info('API_REQUEST', auditLog)

  // Log on finish (with duration)
  res.on('finish', () => {
    logger.info('API_RESPONSE', {
      ...auditLog,
      statusCode: res.statusCode,
      duration: Date.now() - startTime
    })
  })

  next()
}

Rate Limiting by Endpoint

const rateLimits = {
  '/api/login':     { limit: 5,  window: '1m' },  // Anti brute-force
  '/api/transfer':  { limit: 10, window: '1h' },  // Fraud limit
  '/api/balance':   { limit: 60, window: '1m' },  // Normal use
  '/api/verify':    { limit: 3,  window: '1d' },  // Expensive APIs (KYC)
}

Practice

โ†’ REST API with Express


Useful links