top of page

Using ProducesResponseType to write a better Web API actions in .Net Core

Motivation

I used to create API actions that return only one type most of the time, for example the GetProduct action would return Product class.

API action sample


But, what if the product cannot be found? Is it a good idea to return null or an exception? let’s think of it from the API consumer point of view, front end developers definitely don’t want to dig into our code to know the expected results in order for them to handle call response properly.


It would be much better for them to use tools like Swagger to help them understand the capabilities of our API without skimming the code.


But that’s not enough, the GetProduct action, doesn’t tell the consumer enough about itself, for instance, what would the action return if something went wrong? the product is not found? or there is a request validation error?


All swagger can tell us that the action returns an object of type Product and status code 200.

Swagger single response



Using ProducesResponseType

Well, the ProducesResponseType attribute comes in handy, but first let’s change the action return type into ActionResult<> or IActionResult, this would allow the action to return different result types without build errors. The updated code would look like:

Action returns different types


As can be seen in the screenshot above, the action might return either a ValidationProblem, Product or NotFound, however the consumer might not have access to the source code and we don’t want to waste their time searching for possible action response types.


This is where ProducesResponseType comes into play, add a separate attribute for every expected response type as in the below:

ProducesResponseType attributes


Looking at swagger now, we can see this action has three possible responses and the consumer can now call this API gracefully without nightmares.

Swagger multiple responses


Note that since we used ActionResult<Product>, the type parameter can be excluded on the attribute since it can be inferred from the T in ActionResult<T>, otherwise, we would need to change the action as in below:


using IActionResult


Source code available on github.


Conclusion:

In this article, we passed quickly on the usage of ProducesResponseType attribute and Action return types and how it helps the API consumer through exposing the API capabilities.



Source: Medium - Mohammed Hamdan


The Tech Platform

0 comments

Comentários


bottom of page