Krock
Krock

Reputation: 435

REST API - Design a resource as a primary and subresource

I have a specific case in my domain model and now I have some difficult to design this situation in the rest way.

I have 3 entities in my domain: order, seller and company

Company is like a small company that belongs a another company (bigger), like a brand. Ex: Zappos is a brand of Amazon.

Seller is a company that can be sell products in a brand portal/site, ex: Market Place.

And finally, Order can belong to a brand (ex: Amazon or Zappos), or to a seller.

I thought in the Order entity as a primary resource of my API:

GET order?status=NEW
GET order/{id}

The problem is: how can I design my API, for example, to retrieve all opened Orders of a Brand or of a Seller?

I cannot create in this way (below) because I will have two subresources called "order" with two differents primary resources:

GET seller/{id}/order?status=NEW
GET company/{id}/order?status=NEW

If I create in this way (below) I can't retrieve the orders filtering by a seller or a company:

GET order?status=NEW

The other problem of this approach is that because an order always belongs to a resource (company or seller) so it seems strange this resource exist alone, as a primary resource.

Whats is the best way to solve this problem?

Upvotes: 0

Views: 1037

Answers (1)

brandonscript
brandonscript

Reputation: 72865

Consider separating your data in a relational manner so that you can do:

GET /orders
GET /sellers
GET /companies

And:

GET /orders/{id}
GET /sellers/{id}
GET /companies/{id}

Each of these will return what you define to be the default number of rows, in the default sort order, or if id is specified, that particular row.

When you need to build relational queries, you can do:

GET /orders/?status=new&brand=zappos
GET /sellers/?status=new&company=amazon
GET /sellers/?status=closed&company=amazon&limit=10

Alternatively, if you need a more advanced relational query, you could design your back end to handle simple queries:

urlencode this: status==new,date_created>1386652468

GET /orders/?ql=status%3D%3Dnew%2Cdate_created%3E1386652468

Not knowing your constraints, I can't necessarily recommend this as the best/only approach, but separating the data like this is API best practice. You can control what brands are visible depending on who is logged in. What happens if you need someone to administer multiple brands?

Upvotes: 1

Related Questions