Francois Taljaard
Francois Taljaard

Reputation: 1477

HTTP API operations calling each other

Is it ok/acceptable to re-use public API operation between methods?

Say I have one method (GET api/something) and in that method I call internal (GET api/somethingElse).

Internally meaning I instantiate the class and call the method.

Upvotes: 0

Views: 275

Answers (1)

CodeCaster
CodeCaster

Reputation: 151634

As @David says and as explained in Access one web api controller from another, Call WebApi controller from another controller, and so on, you shouldn't instantiate controllers in controllers.

An HTTP API is (supposed to be) just a very thin layer to map an HTTP request to business logic, perhaps performing some authentication and authorization along the way.

A typical GET method in an API controller should look like this:

public SomeModel Get(int id)
{
    var model = _repository.Get(id);
    return model;
}

So if you do this:

public SomeModel Get(int id)
{
    var database = new Database();
    var record = database.SomeModels.Get(id);
    record.FooProperty = DoSomeLogic();

    // and so on

    return record;
}

And in another method GetSomethingElse, maybe even in an other controller, you want to access this logic, then you should look into abstracting everything that happens in this method into a separate class, in my former code referenced through the _repository variable.

Then you can reuse the logic between controllers and action methods.

Upvotes: 3

Related Questions