The Django web framework has a Browsable API and I would like to implement something similar in my ASP.NET (with ReactJS) application. Essentially, suppose that there's an API endpoint called api/test; I would like to be able to navigate to https://.../api/test in a web browser and be presented with a web page (React component) that contains what api/test normally returns but in a better, human-readable format like Django does. But when accessed as an API, it returns the content without the surrounding HTML page. The simple controller would look like:
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet]
[Produces("text/json")]
public IList<string> Get()
{
return new string[]
{
"hello",
"world"
};
}
}
It seems that something similar to Content Negotiation would work. So, I would either have to implement a custom formatter (which I'm not sure is the right approach) or make a middleware of my own.
Does this sort of thing already exist somehow? Any suggestions on how to implement it if it doesn't already exist? Thanks in advance!
You could use a tool like Swagger.
Swashbuckle is a Nuget package that adds Swagger to your application. It adds a couple of dependencies as well as a configuration file in your
App_Startfolder.After adding the package, you can browse to
http://whateveryourappnameis.com/swaggerand see auto-generated documentation for your API. Here is a sample snapshot from an image service I recently created:As you can see, it even generates forms to submit requests so you can test your API!
It also supports additional configuration to customize your documentation.