Correct return type from web API

Viewed 3083

I am creating a c# .net core 2.2 web API for my next project. My question is when returning data should I return the object or IActionResult OK(returnObject)?

The reason I ask is I am using swagger and swagger studio to create my models for an Angular front end. If I return an IActionResult from the API the returned view models are not detailed in the swagger.json file so I would have to code these in the angular application. If I return whatever object is created the model is created in the swagger.json.

What practice should I follow to return data from an API in this case?

2 Answers

You do want to return IActionResult(object) but you are not quite done.

Annotate your controller with the ProducesAttribute and annotate your method with the ProducesResponseTypeAttribute:

[Produces("application/json")]
public class SomethingController
{
    [ProducesResponseType(typeof(YourObject), (int)HttpStatusCode.OK)]
    public IActionResult GetThing(int id)
    { ... }
}

This allows Swagger UI to know what to expect and document it appropriately. Shown above is for a synchronous method; it works for asynchronous as well.

Related