-
Notifications
You must be signed in to change notification settings - Fork 4
Controllers and Response Objects
Creating your response objects
ASP.NET Core will automatically map a c# object that is returned from a controller into a JSON response object (including camel casing the field names). So when creating the response objects they need to match the desired response from the API. As Hackney follows an API first approach, there should already be a planned swagger document to refer to in Hackney Swagger Hub account
Auto-generated swagger docs
We use swashbuckle to auto-generate swagger documentation, based on the code in the controller class and the response objects. You can see the docs that the API has produced by going to baseurl/swagger/index.html (http://localhost:5000/swagger/index.html if running the API locally).
You can add extra documentation and detail to your swagger docs by adding XML comments to the code. Documentation on which how to write these comments and how they render in the swagger UI can be found in Microsoft's documentation or swashbuckle's documentation.
Here is an example of a controller method with some appropriate XML comments.
/// <summary>
/// Find a household by uprn
/// </summary>
/// <response code="200">Success. A household for the given UPRN is returned</response>
/// <response code="400">The UPRN supplied was invalid. UPRN's should contain only numeric characters</response>
/// <response code="404">No household was found for the given uprn</response>
/// <param name="uprn">The Unique Property Reference Number for the household you are interested in</param>
[ProducesResponseType(typeof(HouseholdInformation), StatusCodes.Status200OK)]
[HttpGet]
[Route("/household/{uprn}")]
public IActionResult ViewRecord(string uprn)
{
try
{
return Ok(_getHouseholdByIdUseCase.Execute(uprn));
}
catch (FormatException)
{
return BadRequest();
}
catch (HouseholdNotFound)
{
return NotFound();
}
}Here is an example of a response object with some appropriate XML comments.
public class HouseholdInformation
{
/// <example>
/// 4 Green Road
/// </example>
public string AddressLine1 { get; set; }
/// <example>
/// Hackney
/// </example>
public string AddressLine2 { get; set; }
/// <example>
/// London
/// </example>
public string AddressLine3 { get; set; }
/// <example>
/// E8 6TH
/// </example>
public string PostCode { get; set; }
/// <example>
/// 1000000000
/// </example>
public string Uprn { get; set; }
}