Search code examples
apiasp.net-web-apiurl-routing

Defining routing for HttpGet(Students/{SubjectId}) vs HttpGet(Students/{SectionId})


I have two actions in a controller that return a list of Students:

  • HttpGet(Students/{SubjectId}) - returns Students of a Subject
  • HttpGet(Students/{SectionId}) - returns Students of a Section.

When I am calling the Students/{SectionId}, the call is received in Students/{SubjectId}. Looks like I am missing a fundamental concept of how the request is resolved.

How should my API handle this call? I would not prefer to add extra parameters in the routing path.


Solution

  • If SubjectId and SectionId are the same type (e.g. integers) then in Web API you should not expose multiple methods with the same signature. i.e. GET Students/{int}. Web API has no way to route calls such as GET Students/1234 to one or other controller method as their routes both match the URL requested.

    Even if their types are different or the format of the strings is such that you could implement complex routing logic to ensure that the desired method is called then I still believe you should re-think your endpoints as the API as described is not RESTful.

    REST methods should be entity-based. Thus the entity Students would typically have a GET at its root that would return all Students i.e.:

    GET Students
    

    To get a single student you would expose an endpoint that takes the unique student ID. i.e.

    GET Students/{StudentId}
    

    However if you wanted to return a filtered list of students by SubjectId or SectionId you would typically do this via the querystring. i.e

    GET Students?Section=SectionId
    GET Students?Subject=SubjectId
    GET Students?Section=SectionId&Subject=SubjectId
    

    Or if you see students as a logical child of the subject/section you could expose:

    GET Sections/{SectionId}/Students
    GET Subjects/{SubjectId}/Students