Chapter 5: APIs
1. Fundamentals of APIs
- Services expose operations through interfaces using business logic
- Adapters translate between IPC mechanisms and interface calls
- Communication can be direct (client-server) or indirect (through broker)
2. Communication Patterns
- Request-Response Model:
- Client sends request message
- Service returns response message
- Can be synchronous (blocking) or asynchronous (non-blocking)
3. Data Formats
- Textual (JSON): Human-readable but verbose
- Binary (Protocol Buffers): More efficient but not human-readable
- Format affects:
- Serialization speed
- Human readability
- Evolution capability
4. HTTP Protocol
- Components:
- Start line (request/response info)
- Headers (metadata)
- Body (payload)
- Versions:
- HTTP 1.1: Text-based, sequential
- HTTP 2: Binary, multiplexed
- HTTP 3: UDP-based, improved performance
5. Request Methods (CRUD)
Method | Purpose | Safe | Idempotent |
---|---|---|---|
GET | Read | Yes | Yes |
POST | Create | No | No |
PUT | Update | No | Yes |
DELETE | Delete | No | Yes |
6. Status Codes
- 2xx: Success (200 OK)
- 3xx: Redirection (301 Moved)
- 4xx: Client Errors
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 5xx: Server Errors
- 500: Internal Error
- 502: Bad Gateway
- 503: Service Unavailable
7. Resource Design
- Resources identified by URLs
- Example: https://example.com/products?sort=price
- Nested resources: /products/42/reviews
- Keep URLs simple and intuitive
8. OpenAPI Specification
- Formal API definition using YAML
- Defines:
- Endpoints
- Methods
- Parameters
- Response schemas
- Generates documentation and client SDKs
9. API Evolution Best Practices
- Avoid breaking changes
- Two types of breaking changes:
- Endpoint level (URL changes)
- Message level (schema changes)
- Version APIs using:
- URL prefixes (/v1/products)
- Custom headers (Accept-Version: v1)
- Content negotiation
- Maintain backward compatibility
- Use tools to detect breaking changes
10. Key Principles
- Use REST for public APIs
- Implement proper error handling
- Consider caching strategies
- Plan for evolution and versioning
- Document thoroughly using OpenAPI
- Keep interfaces simple and consistent
- Consider security (HTTPS by default)