Search code examples
c#asp.net-web-apiroutesattributerouting

What is the best practice for routing relationships in a REST api?


Lets say I have two objects, Users and Appointments, where Users may have one or many appointments.

I am curious if I should allow consumers of the API to 'filter' by users from the Appointments controller. Here are the calls I have in mind for the GET operations:

Users Controller
GET
api/Users
api/Users/{userId}
api/Users/{userId}/Appointments
api/Users/{userId}/Appointments/{appointmentId}

Appointments Controller
GET
api/Appointments/
api/Appointments/{appointmentId}

I am curious if it is a good idea (good practice) to implement filters for the users on the Appointments controllers... So the calls above would become:

Appointments Controller
GET
api/Appointments/{userId:int?}
api/Appointments/{appointmentId}

In the above calls I've added an optional querystring parameter for the userId that will default to null. This would allow a caller to either GET all appointments, or to get appointments by userId.

I guess I am not really certain what is considered a best practice for objects with relationships.


Solution

  • If you want simplicity I would suggest

    Users GET

    api/users
    api/user/{id}
    api/user/{id}/appointments
    

    Appointments GET

    api/appointments
    api/appointment/{id}
    

    And from the looks of it api/Appointments/{userId:int?} doesn't read well since a user has appointments and an appointment only has a single user. In the case of the endpoint api/Appointments/{appointmentId} I'm not sure what AppointmentId is but if it's an int you'll have to do some funky stuff to look up an appointment or a user based on an int, in which case the ID's could be the same.

    Getting too far into the depth of an object tree can get confusing as far as url structure.