Fabio Picheli Fabio Picheli - 1 month ago 9
Java Question

Best URL structure for relation many-to-one

I'm using Spring Boot (generated by JHipster).

I have the following services:

/api/market/
/api/market/:id


and

/api/product/
/api/product/:id


all those with GET, PUT, POST and DELETE. But I need to implement one more specific service.

This services should return all the products inside the market
X
. But to do that, I was thinking to pass in the URL path this call:
/api/product?marketID=1
, but I will have to make a select in the market table and then get the products (will be easier search in only one table by
market_id
field).

I don't know if this URL is the best structure and also this kind of search. I know you can search of a specific field on the table the you do a filter, but I tested and I was not able to get a relation field.

Answer

I'd like to make a recommendation for how to structure your API, then provide a possible answer to your question.

Typically, RESTful APIs follow the plural-singular principle: given all markets (plural part), find market with id 5231422 (singular part). Reflect that in your URLs with /api/{plural-noun}/{singular-identifier}. So your API would end up looking more like this:

/api/products  (all products in the system)
/api/products/:productId  (a single product in the system)
/api/markets  (all markets in the system)
/api/markets/:marketId  (a single market in the system)

To answer your question, then: I recommend you use the "Russian stacking doll" URL design. It appears that your design suggests that a single Market can contain several products in it. Thus you might find this kind of URL a bit clearer: /api/markets/:marketId/products, which fetches all products within that market.

Comments