Junior — Middle
What methods and principles can be used to implement REST API when designing web services?
sobes.tech AI
Answer from AI
REST API is built on the principles of REST (Representational State Transfer), which include:
- Using standard HTTP methods: GET (retrieve data), POST (create), PUT/PATCH (update), DELETE (delete).
- Resource-oriented architecture: each object or entity has a unique URI.
- Statelessness: each request contains all the necessary information.
- Using standard HTTP response codes to indicate the result of an operation.
When designing a REST API:
- Define resources and their hierarchy in the URL, for example, /users/{id}/orders.
- Use the correct HTTP methods for operations.
- Data format is usually JSON.
- Add pagination, filtering, and sorting if necessary.
Example of a simple REST API in Java using Spring Boot:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// logic to get user
}
@PostMapping
public User createUser(@RequestBody User user) {
// logic to create user
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
// logic to update user
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
// logic to delete user
}
}