Search code examples
restentity-relationshipapi-design

Rest API resource design for many-to-many relation


Post can be in many Categories and Sections. Category and Section can have many Posts

To list sections/categories using:

GET /posts/categories
GET /posts/sections

seems to be better design than:

GET /categories
GET /sections

But how to ask for Posts from sections/categories ?

  • This seems to be awkward (or maybe it isn't ?):

    GET /posts/sections/{id}/posts

  • These can be problematic:

    GET /posts?section={id}

    because I already have couple filters, so I end with:

    GET /posts?section={id}&filter1={f1}&filter2={f2}....

Any suggestions ?


Solution

  • I personally would use the query parameter approach to filter the posts collection given that it's a many to many relationship and the resources can be managed independently:

    GET /posts?section={id}
    

    And I would probably use the following mapping for categories and sections:

    GET /categories
    
    GET /sections
    

    If, for example, a collection of posts belongs to just a single category, I would use:

    GET /categories/{id}/posts