REST APIs
REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs use HTTP methods and are typically simpler than SOAP services.REST Principles
REST is based on six fundamental constraints:Client-Server Architecture
Separation of concerns between the user interface (client) and data storage (server).
Stateless
Each request contains all information needed to process it. The server doesn’t store client context between requests.
Layered System
Client cannot tell if it’s connected directly to the server or through intermediaries.
HTTP Methods
RESTful APIs use HTTP methods to indicate the desired action:| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve resource(s) | GET /api/products |
| POST | Create new resource | POST /api/products |
| PUT | Update entire resource | PUT /api/products/13 |
| PATCH | Partial update | PATCH /api/products/13 |
| DELETE | Remove resource | DELETE /api/products/13 |
REST vs SOAP Comparison
- REST Advantages
- SOAP Advantages
- Simpler: Easier to learn and implement
- Flexible formats: JSON, XML, HTML, plain text
- Performance: Smaller message size, especially with JSON
- Caching: Built-in HTTP caching support
- Browser-friendly: Easy to test with browser tools
REST API Design
Resource Naming
Use nouns (not verbs) for resource paths:HTTP Status Codes
Use appropriate status codes to indicate the result:| Code | Meaning | Usage |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Missing or invalid credentials |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource doesn’t exist |
| 500 | Server Error | Internal server error |
Building a Simple REST API in PHP
Here’s a basic REST API for managing products:api.php
Consuming REST APIs
Using cURL
Using file_get_contents
For simple GET requests:JSON Format
REST APIs typically use JSON for data exchange:API Authentication
- API Key
- Bearer Token
- Basic Auth
Error Handling
Best Practices
Key REST API Best Practices:
- Use nouns for resources, not verbs
- Use plural names for collections
- Use HTTP methods correctly
- Return appropriate status codes
- Version your API (e.g.,
/api/v1/products) - Use pagination for large datasets
- Implement rate limiting
- Provide clear error messages
- Use HTTPS in production
- Document your API thoroughly
Course Context
In TEMA-06, you’ll compare REST and SOAP approaches, understanding when to use each:- SOAP projects: TAREA-06 implements a product catalog with SOAP services
- REST concepts: Applied in API integration in TEMA-08
- Hybrid approaches: Some projects may use both patterns
Next Steps
SOAP Introduction
Compare with SOAP web services
API Integration
Learn to consume external APIs