Home
Do you define your response types?
  v1.0 Posted at 25/05/2019 12:24 PM by Tiago Araujo

It is important to define your response types.

bad-no-response-types.jpg
dd>​Figure: Bad example – no response types
good-response-types.png
Figure: Good example – Response types (in .NET)


/// <summary>
/// Returns the nth number in the fibonacci sequence.
/// </summary>
/// <param name="n">The index (n) of the fibonacci sequence</param>
/// <returns>Returns the nth fibonacci number.</returns>
/// <response code="200">int64</response>
[HttpGet]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ResponseCache(CacheProfileName = DefaultCacheProfile.Name)]
[Produces("application/json", "text/json")]
public ActionResult<long> Get(long n)
{
_logger.LogInformation($"Fibonacci number {n} requested");
if(!_fibonacciSolver.CanSolve(n))
return new BadRequestResult();
try
{
return _cache.GetOrAdd($"Fibonacci{n}", () => _fibonacciSolver.Solve(n));
}
catch (ArgumentOutOfRangeException)
{
return new BadRequestResult();
}
}

Figure: Good example for swashbuckle - Even b​etter if you have .NET Core 2.1 use the strong typed ActionResult – see yellow​​

        [HttpGet]
        [SwaggerResponse(HttpStatusCode.OK, typeof(long))]
        [SwaggerResponse(HttpStatusCode.BadRequest, typeof(void))]
        public ActionResult<long> Get(long n)
        {
            _logger.LogInformation($"Fibonacci number {n} requested");
            
            if(!_fibonacciSolver.CanSolve(n))
                return new BadRequestResult();
 
            try
            {
                return _cache.GetOrAdd($"Fibonacci{n}", () => _fibonacciSolver.Solve(n));
            }
            catch (ArgumentOutOfRangeException)
            {
                return new BadRequestResult();
            }
        }

Figure: Good example for nswag - Even better if you have .NET Core 2.1 use the strong typed ActionResult – see yellow​​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: