What is an API?
September 6, 20256 min read
API (Application Programming Interface) is a contract between different software components that defines how they communicate with each other.
API Architecture Styles
RESTful API Design Principles
Resource Naming Conventions
URL Structure Examples:
GET /api/v1/users # List users
GET /api/v1/users/123 # Get user 123
POST /api/v1/users # Create user
PUT /api/v1/users/123 # Replace user 123
PATCH /api/v1/users/123 # Update user 123
DELETE /api/v1/users/123 # Delete user 123
# Nested Resources
GET /api/v1/users/123/orders/456
GET /api/v1/posts/789/comments
API Versioning Strategies
Request/Response Design
Authentication & Authorization
JWT Token Example:
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"sub": "user123",
"name": "John Doe",
"roles": ["admin", "user"],
"exp": 1719532800
}
// Usage
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Error Handling
Error Response Format:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid request parameters",
"details": [
{
"field": "email",
"issue": "Invalid email format"
}
],
"timestamp": "2024-01-15T10:30:00Z",
"path": "/api/v1/users",
"request_id": "req_abc123"
}
}
Pagination Patterns
Pagination Response:
{
"data": [...],
"pagination": {
"total": 1000,
"page": 2,
"per_page": 20,
"total_pages": 50,
"links": {
"first": "/api/users?page=1",
"prev": "/api/users?page=1",
"next": "/api/users?page=3",
"last": "/api/users?page=50"
}
}
}
Filtering, Sorting & Search
Rate Limiting
Caching Strategy
API Documentation (OpenAPI/Swagger)
openapi: 3.0.0
info:
title: User API
version: 1.0.0
paths:
/users/{id}:
get:
summary: Get user by ID
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
200:
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/User'
404:
description: User not found
Webhooks Design
Webhook Payload:
{
"id": "evt_1234567890",
"type": "order.created",
"timestamp": "2024-01-15T10:30:00Z",
"data": {
"order_id": "ord_abc123",
"amount": 99.99,
"customer_id": "cust_xyz789"
},
"signature": "sha256=a1b2c3d4..." // HMAC signature
}
GraphQL vs REST
GraphQL Query Example:
query GetUser {
user(id: 123) {
name
email
posts(limit: 5) {
title
content
}
followers {
count
}
}
}
Idempotency
Idempotent Request:
POST /api/v1/payments
Idempotency-Key: 7b4a8c1d-f3e2-4a5b-9c6d-1e2f3a4b5c6d
Content-Type: application/json
{
"amount": 100.00,
"currency": "USD"
}
API Security Best Practices
API Lifecycle
Performance Optimization
API Gateway Pattern
Response Format Standards
Success Response:
{
"success": true,
"data": {
"id": 123,
"name": "John Doe",
"email": "john@example.com"
},
"meta": {
"timestamp": "2024-01-15T10:30:00Z",
"version": "1.0"
}
}
Collection Response:
{
"success": true,
"data": [...],
"meta": {
"pagination": {...},
"filters": {...},
"sorting": {...}
},
"links": {
"self": "/api/users?page=2",
"next": "/api/users?page=3"
}
}