What is the correct restful API design when we have optional behavior?

JavaDeveloper :

I have use case where a class of students is broken down into teams. class has a classId and team has a teamId.

I have the following options:

  1. Create 2 endpoints:

    @GET
    @Path("/schoolMetadata/byClass/{classId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getMetadataByClassId(
    

and

    @GET
    @Path("/schoolMetadata/byTeam/{teamId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getMetadataByTeamId(
  1. Second implementation would be using query param.

    @GET
    @Path("/schoolMetadata/by/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getMetadataById(
        @QueryParam("classId") final Id classId
        @QueryParam("teamId") final Id groupId) {
        if (classid != null) {
        }  else {
        }
    }
    

Which of the 2 approaches is better ?

Tom Drake :

The idea behind RESTful urls is that they should represent 'resources' which are singular or plural nouns. Resources that represent a 'collection' of like things should be plural. You have indicated that school metadata can be obtained for either a class id or a team id. That sound like classes and teams might be considered as 'resources', regardless of whether they are both modeled internally as a 'schoolMetadata'. Without any other information, I might suggest something like:

  • classes/{classId}
  • teams/{teamId}

If you're using jaxrs, it would natural to wind up with urls that look something a little more like this:

  • schoolMetadata/resources/classes/{classId}
  • schoolMetadata/resources/teams/{teamid}

You might also want to implement:

  • schoolMetadata/resources/classes to produce a list of 'classes'. Query params could be used here to facilitate search options.
  • schoolMetadata/resources/teams to produce a list of 'teams' . . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81657&siteId=1