Search code examples
restspring-mvcspring-restcontrollerspring-rest

how to write compound REST methods, and REST methods of verbs in spring?


For example I have UserController with methods:

GET /api/users -- get all users
GET /api/users/1 -- get concrete users
POST /api/users -- create concrete users
PUT /api/users/3 -- update concrete users

It is classic REST. But I have 2 questions.

  1. How should the method look like that makes payment in REST archetecture?

like this? - POST /api/payments/pay - But pay is verb

or login of user - POST /api/users/3/login???

  1. I have 2 controllers - MarketController and CarsController with methods:

GET /api/markets/3 -- get market with id = 3

GET /api/cars/1 -- get car with id = 1

Client try get concrete car from concrete market:

GET /api/markets/3/cars/1 -- in which controller should I write this?


Solution

  • Answer for the question #1

    That's a misconception: REST doesn't care about the URI design. However, once the central piece of the REST architectural style is the resource, it makes sense that the URI that identifies a resource contains a noun instead of verb.

    To avoid verbs, you could use just /api/payments. A POST to that URL will create a payment with the representation sent in the request payload.

    For the authentication resource, you could use /api/auth, for example.

    Answer for the question #2

    It seems to be a method for the MarketController, which is mapped to /markets.

    But keep in mind that your controllers shouldn't perform any business logic. Instead, it should delegate to a service.