shieldstroy
shieldstroy

Reputation: 1327

How should I organize endpoints to be RESTful?

Let's say I have two types of resources I want in my API: person and class. These two have a many-to-many relationship.

As such, would I expect to be able to interact with the following endpoints:

  1. /api/persons/1/classes -- list of classes for this person
  2. /api/classes/1/persons -- list of people in this class.

What is the best way to organize these in my code?

Here are some possible choices I have thought of, but I can see downsides to each one. (Using C#, but my question applies more generally).

PersonsController.cs 

[Route("api/persons/{personId}/classes")]
[AcceptVerbs("GET")]
public List<SchoolClass> ListClassesForPerson(string personId)
{
    //return result of PersonsService.ListClassesForPerson(personId)
}

And have the opposite in my ClassController.cs.

The downside to this approach is that now I have a PERSON controller and PERSON service returning a list of Classes... seems icky.

An alternative might be:

PersonsController.cs 

[Route("api/persons/{personId}/classes")]
[AcceptVerbs("GET")]
public List<SchoolClass> ListClassesForPerson(string personId)
{
    //return result of ClassesService.ListClassesForPerson(personId)
}

But now I am accessing the CLASS service from my PERSON controller, also seems very icky.

I think I have decided that the route /api/persons/{personId}/classes should actually be handled by the ClassController.cs class even though it's describing a resource on a person... but I'm still not sure if this is the best thing to do.

What is the best practice for this situation? Am I missing something obvious?

Upvotes: 0

Views: 433

Answers (1)

arjabbar
arjabbar

Reputation: 6404

I wouldn't waste too much time trying to build the prettiest API ever. I see nothing wrong with using a ClassService inside of your Person controller. If you're going to try and limit yourself to only using services with the same name as your controller, you're going to spend a lot of time trying to work around something that inevitable will not be a huge issue.

And I also think that a service class should just be a helper class when dealing with the subject matter. So if you need to get a list of classes filtered by a particular field, then that logic should be in a ClassService. As long as you think someone else will not be confused by looking at your code, then you're fine.

Sidenote:

The only small issue I see is with the names of your resources. I've worked on an API with similar subjects. I ended up changing classes to lectures, since class is a reserved word in most object-oriented languages and I switched person to student since the pluralization of that could get a little tricky.

Upvotes: 1

Related Questions