API Design
These are the RESTful API design principles I follow when designing APIs.
RESTful API Basic Principles
HTTP Methods
Each HTTP method has a clear meaning:
| Method | Purpose | Idempotent | Safe |
|---|---|---|---|
GET | Retrieve resource | O | O |
POST | Create resource | X | X |
PUT | Full update resource | O | X |
PATCH | Partial update resource | X | X |
DELETE | Delete resource (Soft Delete) | O | X |
Idempotent: Same result even if the same request is sent multiple times Safe: Does not change server state
URL Design Rules
| |
HTTP Status Codes
Success Responses (2xx)
| |
Client Errors (4xx)
| |
Server Errors (5xx)
| |
Request/Response DTOs
Request DTO
| |
Response DTO
| |
List Response (Pagination)
| |
Error Responses
Standard Error Response Format
| |
Validation Error Handling
| |
Business Error Handling
| |
API Versioning
URL Versioning (Recommended)
| |
Header Versioning
| |
Filtering, Sorting, Searching
Filtering
| |
Sorting
| |
Searching
| |
Validation Layer
Request DTO Validation
| |
Custom Validation
| |
Business Validation (Service Layer)
| |
Security (Enhanced)
Never Store Passwords in Plain Text
| |
XSS Prevention
| |
CSRF Token Usage
| |
JWT Token Security
| |
Authentication Header
| |
Input Sanitization
| |
Rate Limiting
| |
CORS Configuration
| |
Checklist
When designing APIs:
- Follows RESTful principles? (nouns, plural, HTTP methods)
- Uses appropriate HTTP status codes?
- Includes version in URL? (/api/v1/…)
- Uses Request/Response DTOs? (No direct Domain exposure)
- Uses consistent error response format?
Validation:
- Request DTOs have Bean Validation annotations?
- Using @Valid in Controller?
- Business validation performed in Service layer?
- Custom Validation implemented when necessary?
- Input sanitization performed?
Security:
- Using Prepared Statements to prevent SQL Injection?
- HTML escape processing to prevent XSS?
- Using CSRF tokens? (for stateful)
- Not storing passwords in plain text? (Using BCrypt)
- Using strong algorithms for JWT tokens? (HS512 or above)
- Enforcing HTTPS?
- Not logging sensitive information?
- No sensitive information in exception messages?
- CORS properly configured?
- Rate Limiting applied?
Authentication/Authorization:
- Authentication applied to APIs that require it?
- Role-Based Access Control (RBAC) implemented?
- Using stateless session management? (JWT)
- Appropriate token expiration time?
Error Messages:
- Error messages are clear?
- Using consistent error response format?
- Specifying which fields have validation errors?
- No sensitive information in error messages?
Pagination and Filtering:
- Pagination applied to list APIs?
- Clear pagination parameters (page, size)?
- Clear filtering parameters?
- Sorting options provided?
- Maximum page size limit enforced? (e.g., max 100)