2

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?

1 Answer 1

4

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
}
  • Don't forget the implementation inside the {} brackets.
  • The example method 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.
  • I suggest you rename the class User to UserController, because the User is a suitable name for the returned entity.
Sign up to request clarification or add additional context in comments.

2 Comments

a stupid question: can i use order controller for that? I known this not logical, they have separate business but my mind is involved.
No question is stupid. It depends if the /users/{user_id}/orders/{order_id} would return the same as /orders/{order_id} - whether the order_id is a number of the user's order or a number of all the orders. Generally, I don't recommend to call one controller from another.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.