Junior — Middle
What limitations and restrictions should be considered when designing a REST API?
sobes.tech AI
Answer from AI
When designing REST APIs, the following constraints are important to consider:
- Standardization of HTTP methods: use GET, POST, PUT, DELETE, and others according to their purpose.
- Resource identification: URIs should be understandable and reflect the data structure.
- Response statuses: correctly use HTTP codes to inform the client about the request result.
- Security: provide authentication and authorization, for example, through OAuth or JWT.
- API versioning: to avoid breaking compatibility when making changes.
- Size and time limitations: consider limits on request size and processing time.
- Idempotency: PUT and DELETE methods should be idempotent.
An example of a simple REST controller in Java using Spring Boot:
@RestController
@RequestMapping("/api/items")
public class ItemController {
@GetMapping("/{id}")
public ResponseEntity<Item> getItem(@PathVariable Long id) {
// logic to retrieve the object
return ResponseEntity.ok(item);
}
@PostMapping
public ResponseEntity<Item> createItem(@RequestBody Item item) {
// logic to create the object
return ResponseEntity.status(HttpStatus.CREATED).body(createdItem);
}
}