REST API Fundamentals
REST (Representational State Transfer) is an architectural style for building web services. It uses HTTP methods to perform operations on resources identified by URLs. A well-designed REST API is intuitive, scalable, and maintainable.
HTTP Methods (Verbs):
Retrieve resources
Safe and idempotent. Never modify server state.
Create new resources
Not idempotent. Can have side effects.
Replace entire resource
Idempotent. Requires complete resource.
Partial resource updates
Modify specific fields without full replacement.
Remove resources
Idempotent. Removes identified resource.
Resource Naming Conventions:
- ✓ Use nouns for resources:
/users,/products - ✓ Use plural nouns:
/usersnot/user - ✓ Use hyphens for multi-word names:
/user-profiles - ✓ Use lowercase:
/api/v1/usersnot/API/V1/Users - ✓ Nest resources for relationships:
/users/123/posts - ✗ Don't use verbs in URLs: avoid
/getUseror/createPost
API Versioning Strategies
API versioning allows you to evolve your API without breaking existing clients. Choose a versioning strategy early and stick with it.
1. URL Path Versioning
Version embedded in the URL path.
GET /api/v1/users
GET /api/v2/users
Pros: Clear, easy to cache
Cons: URL bloat, breaks REST principles
2. Header Versioning
Version specified in custom header.
Accept: application/vnd.myapi.v1+json
API-Version: 2
Pros: Clean URLs, flexible
Cons: Harder to test, caching issues
3. Query Parameter Versioning
Version as a query parameter.
GET /api/users?version=2
Pros: Optional versioning support
Cons: Easy to miss, can cause confusion
Authentication & Authorization
Secure your API with proper authentication and authorization mechanisms. Never trust client-provided credentials without verification.
API Key Authentication
Simple key-based authentication for public APIs.
Authorization: Bearer sk_live_abc123xyz
✓ Use for public APIs | ✗ Avoid for sensitive data
OAuth 2.0
Industry standard for delegated authorization.
Perfect for third-party integrations and user delegation.
✓ Secure, industry standard | ✓ User-friendly | ✗ More complex
JWT (JSON Web Tokens)
Self-contained tokens for stateless authentication.
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
✓ Stateless, scalable | ✓ Works with microservices | ✗ Token revocation complexity
Proper Error Handling
Return meaningful HTTP status codes and consistent error responses. Help developers debug issues quickly.
HTTP Status Codes
2xx Success - 200 OK, 201 Created, 204 No Content
3xx Redirection - 301 Moved, 302 Found, 304 Not Modified
4xx Client Error - 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict
5xx Server Error - 500 Internal Error, 502 Bad Gateway, 503 Service Unavailable
Error Response Format
{
"error": {
"code": "INVALID_REQUEST",
"message": "Email is required",
"status": 400,
"details": {
"field": "email",
"issue": "missing_required_field"
}
}
}
Always include error code, message, status, and details for debugging.
Pagination & Filtering
Large datasets require efficient pagination. Implement filtering, sorting, and limiting to reduce bandwidth and improve performance.
Cursor-Based Pagination
Recommended for large datasets and real-time data.
GET /users?limit=20&cursor=abc123
✓ Efficient for large sets | ✓ Works with real-time data | ✗ More complex
Offset/Limit Pagination
Simple and widely supported.
GET /users?limit=20&offset=40
✓ Simple to implement | ✗ Inefficient for large offsets | ✗ Bad for real-time data
Filtering & Sorting
GET /products?category=electronics&status=active&sort=-created_at
- ✓ Use query parameters for filters
- ✓ Support multiple sort fields with +/- prefix
- ✓ Document all supported filter fields
- ✓ Include total count in response metadata
Performance Optimization
Fast APIs improve user experience and reduce server costs. Implement caching, compression, and efficient querying.
Caching Headers
Use Cache-Control, ETag, and Last-Modified for browser and CDN caching.
Compression
Enable gzip/brotli compression to reduce response size by 70%+.
Field Selection
Allow clients to request only needed fields: ?fields=id,name,email
Rate Limiting
Implement rate limiting to prevent abuse: X-RateLimit-* headers.
Connection Pooling
Reuse database connections for better performance.
Security Best Practices
Input Validation
- ✓ Validate all input data types and formats
- ✓ Implement max length limits to prevent DOS
- ✓ Sanitize inputs to prevent injection attacks
- ✓ Return specific validation errors
HTTPS Only
- ✓ Always use HTTPS in production
- ✓ Redirect HTTP to HTTPS
- ✓ Use HSTS headers for security
- ✓ Keep SSL certificates up to date
CORS Configuration
- ✓ Only allow trusted origins
- ✓ Avoid wildcard (*) in production
- ✓ Set appropriate methods and headers
- ✓ Use credentials carefully
Data Protection
- ✓ Never log sensitive data
- ✓ Hash and salt passwords
- ✓ Encrypt sensitive data at rest
- ✓ Implement proper access controls
API Documentation
Great documentation is essential for API adoption. Use tools like OpenAPI/Swagger and keep docs updated with code changes.
Documentation Should Include:
- ✓ Endpoints: Full URL, method, description
- ✓ Parameters: Type, required/optional, constraints
- ✓ Responses: Status codes, example payloads
- ✓ Errors: Possible errors and how to handle them
- ✓ Authentication: How to authenticate requests
- ✓ Rate Limits: Limits and reset information
- ✓ Examples: cURL, JavaScript, Python code examples
- ✓ Changelogs: Breaking changes and deprecations
Deploy Your API with Confidence
Build and deploy REST APIs with Spidey Host. Reliable infrastructure with automatic scaling, monitoring, and security included.
Start Hosting Your API