Reputation: 676
I develope RESTful back-end app with spring boot. I find out how to use annotation in the class:
@RestController
@RequestMapping(path = "/users")
public class User{
// rest of code!
}
But every user has orders and any orders has items! So I design rest API like this:
/users /users/{user_id}
/users/{user_id}/orders
/users/{user_id}/orders/{order_id}
/users/{user_id}/orders/{order_id}/items
/users/{user_id}/orders/{order_id}/items/{item_id}
/users/{user_id}/cart
Now, what is best practice or normal implementation for this design in spring boot? How can I handle APIs with Spring Boot?
Upvotes: 2
Views: 2971
Reputation: 44368
Continue and use the annotated method inside the class:
@RestController
@RequestMapping(path = "/users")
public class UserController {
@GetMapping("/{user_id}")
public User getUserById(@PathVariable("user_id") String userId) { }
@GetMapping("/{user_id}/orders")
public List<Order> getOrdersByUserId(@PathVariable("user_id") String userId) { }
@GetMapping("/{user_id}/orders/{order_id}")
public List<Order> getOrdersByIdAndUserId(@PathVariable("user_id") String userId, @PathVariable("order_id") String orderId) { }
// ... and so on
}
{}
brackets. getOrdersByIdAndUserId
is mapped to the GET
method of path /users/{user_id}/orders/{order_id}
where /users
is a common part defined as the class mapping and the rest with the method.User
to UserController
, because the User
is a suitable name for the returned entity.Upvotes: 4