userSteve
userSteve

Reputation: 1644

Is it OK for multiple REST API methods to share same controller class?

Is it best practice to put each distinct Get method in its own controller class, or is it perfectly fine to have multiple (related and non-related) API methods in the same class, if the methods are very simple and uncomplicated.

E.g. these two API methods work fine in the same controller class, but would they be better off in their own class?

If so why?

public class TestController : ApiController
{
    [HttpGet]
    [Route("api/test/ping")]
    public IHttpActionResult Ping()
    {
        try
        {
            return Ok("HELLO");
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

    [HttpGet]
    [Route("api/test/echo/{message}")]
    public IHttpActionResult Echo(string message)
    {
        try
        {
            return Ok(message);
        }
        catch (Exception ex)
        {
            return Content(HttpStatusCode.InternalServerError, ex.Message);
        }
    }
}

Upvotes: 1

Views: 1890

Answers (2)

Nkosi
Nkosi

Reputation: 247088

There is nothing stopping you from having multiple actions in a controller once their routes are distinct and do not cause route conflicts in the current or other controllers.

Take your provided example. You can take advantage of route prefixes for the controller to help with the organizing of similar routes

[RoutePrefix("api/test")]    
public class TestController : ApiController {

    //GET api/test/ping
    [HttpGet] [Route("ping")]
    public IHttpActionResult Ping() {
        return Ok("HELLO");
    }

    //GET api/test/echo/hello%20world
    [HttpGet] [Route("echo/{message}")]
    public IHttpActionResult Echo(string message) {
        if(message == null)
            return BadRequest();
        return Ok(message);
    }
}

Upvotes: 3

Gladen
Gladen

Reputation: 802

Personally I would put related API actions that work that do related work together in 1 single controller class.

In your given example it would be fine to put them together. Another example, say you have a Controller that handles all actions on a User model (Please note not entirely valid code, but hopefully you get the point):

[RoutePrefix("api/users")]
public class UserController: ApiController
{
    [HttpGet]
    public IHttpActionResult GetUsers()
    {
        // GET all users.
    }

    [HttpGet]
    [Route("{id}")]
    public IHttpActionResult GetUserById(int id)
    {
        // GET user by ID
    }

    [HttpPost]
    public IHttpActionResult CreateUser()
    {
        // Create User
    }

    [HttpPut]
    [Route("{id}")]
    public IHttpActionResult UpdateUser()
    {
        // Update User
    }
}

As you can see, all these actions work on the User model, so they fit together in a Controller class.

Upvotes: 2

Related Questions