Search code examples
mongodbrestapiapi-design

RESTful API design advice on getting all A associated with B


I'm trying to design a RESTful API as a side project.

I am also using MongoDB as database

(I'm new to NoSQL design, so I need help, If I have misunderstanding in how documents should be designed).

I have example entities as following:

Event {
    id: string
    name: string
    date: date
    location: location
    subgroups: group[]
}
Group {
    id: string
    owners: user[]
    members: user[]
    parentEvent: event
    posts: post[]
}
User {
    id: string
    Name: string
    attendingGroups: group[]
    owningGroups: group[]
}
post {
    id: string
    parentgroup: Group
}
location {
    id: string
    city: string
}

For above example,

Should I have a designated get call for having all groups associated with the user?

or should I get a user and get the associated groups from the user retrieved?


Solution

  • Depends how you design it. You can embed resources in other resources to save you from N+1 select problem, nothing is against with that.

    Hal+json format is the format you should be embedding resources.

    In REST you can even have ?_embed=groups parameter to embed or not.

    Embedding or not embedding is up to your applications needs, not embedding way = you should design a filter like /groups?user=eralpb to get the groups. Or sub-resources work as well like /users/eralpb/groups should only return my groups.