Tip – REST APIs
Postman is a fantastic tool for building web APIs documentation, test suites, and experimenting with your APIs. It supports OpenAPI specifications, allows you to create mock servers, supports environments, and more.
No matter the tools, there are two major trends in how to design the API contract of a REST API:
- Design the contract first, then build the API (contract-first).
- Build the API, then extract the contract for the code (code-first).
I left a link in the Further Reading section below about Open API.
On the other hand, to use a code-first approach and automatically extract the OpenAPI specifications from the API, we must ensure our endpoints are discoverable by the .NET ApiExplorer.No matter how you do it, in ASP.NET Core, we use classes and struct to represent the data contract of our REST APIs; whether it happens before or after you write the API contract does not matter. Since I prefer to write C# to YAML or JSON, we explore how to leverage Swagger to generate a data contract in a code-first manner next.
In this example, we have a tiny API with two endpoints:
The code doesn’t do much and returns fake data, but it is enough to explore its data contract.
Remember that code is like playing LEGO® blocks, but we connect many tiny patterns used together to create our software and create value. Understanding and learning that skill will lead you beyond just being able to use some canned magic recipe, which limits you to what people share with you.
In this sample, we use the OpenAPI specification to describe our API. To save ourselves from writing JSON and go code-first instead, we leverage the SwagerGen package.
To use SwaggerGen, we must install the Swashbuckle.AspNetCore.SwaggerGen NuGet package.
Here’s the Program.cs file, without the endpoints, showing how to leverage SwaggerGen:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
// Omitted endpoints
app.Run();
The highlighted lines are the only things we must do to use SwaggerGen in a project, which will generate the API contract in the OpenAPI specification for us. The JSON file is very long (113 lines), so I only pasted some snippets in the book for clarity. However, you can navigate to the /swagger/v1/swagger.json URL to access the complete JSON code or open the swagger.json file in the project.
I created the swagger.json file in the project for convenience. The tool does not generate a physical file.