You are currently viewing MinimalAPI with .NET 7 and OpenAPI: A Tutorial
Photo by Pixabay on Pexels.com

MinimalAPI with .NET 7 and OpenAPI: A Tutorial

Part 4 of 5 of the .NET series

Portfolio Project

.NET 7 brings some wonderful bells and whistles for APIs, including MinimalAPI. This article will cover an example of a simple, minimal API you can easily examine via Swagger and OpenAPI.

Spin Up Default App with MinimalAPI

First, spin up an ASP.NET Core Web API, `LabDemo.MinimalApi` or your choice:

Example app uses the template, ASP.NET Core Web API, in Visual Studio 2022, with EnableOpenApi support checked

See how the “Enable OpenAPI support” is checked?

Run Default App

Second, run the default app. Explore the swagger that comes up:

Beautiful!

Feel free to explore changing the in-line mock weather data in the Program.cs.

Switch to Our Mock Data

When you’re ready, let’s change over to our own data.

For this example, we are mocking data the API will return via a json configuration file. You can read more about this approach here.

You can run the app with a breakpoint after where we assign the mock data to confirm it’s being loaded correctly.

Change to Our MinimalAPI Endpoints

Once the data is ready and tested, let’s change the endpoints in Program.cs.

// In the real world, this would be coming from a service — data access, dbContext, or repo, etc
var records = builder.Configuration.GetSection("LabRecords").Get<List<FlattenedLabRecord>>();
// API ROUTING
app.MapGet("/", () => { return records; });
app.MapGet("/LabRecords", () => { return records; })
.WithOpenApi();
app.MapGet("/LabNames", () => { return records?.Select(r => r.Name).Distinct(); })
.WithOpenApi();
app.MapGet("/LabRecords/Search", (string LabName) =>
{
return records?.Where(r => r.Name.ToUpper() == LabName.ToUpper());
})
.WithOpenApi();
// REFERENCE
// If a need exists to bind complex parameters, see https://code-maze.com/aspnetcore-query-string-parameters-minimal-apis/

Validate MinimalAPI Endpoints

Confirm the changes by running in debug in the Development hosting environment (this is the default if you’re launching from Visual Studio).

You should see the following:

Swagger of MinimalAPI endpoints

Add Test Project

How should this app be tested?

If we had more complex logic behind the endpoints, we could certainly do unit testing, considering robust classes or important methods as the units being tested.

However, in this case, we just want to ensure the API is taking requests and returning what data is expected.

So, you can think of it as the app itself being the unit under test, or you can think of the testing as “black box” testing — testing that doesn’t care what’s inside the API, just the behavior of the API.

In this example, add an Xunit test project to the solution, LabDemo.MinimApi.Tests or your choice.

Soultion Explorer showing tests project

Configure Test Project

We want to ensure the test project can see what it’s testing, so add the following lines to the main API app project file:

<ItemGroup>
    <InternalsVisibleTo Include="LabDemo.MinimalAPI.Tests" />
</ItemGroup>

And the test project file needs to reference our API project:

<ItemGroup>
    <ProjectReference Include="..\LabDemo.MinimalApi\LabDemo.MinimalApi.csproj" />
</ItemGroup>

You’ll notice in my tests I’m using a third-party supplment to XUnit called Shouldly. You can install it from Nuget if you choose to use it in your own app.

Solution Explorer showing dependencies

Write Tests

I like to stub out my tests first, like the following. Of course, you can write sets of test at a time as you go, as you add each endpoint, for a more TDD-flavored approach.

        [Fact(Skip ="TBD")]
        public async Task GetLabwork_ShouldRespondOk()
        {
        }

        [Fact(Skip ="TBD")]
        public async Task GetLabwork_ShouldReturnRecords()
        {
        }

What tests you write is up to you, the app requirements, criticality, time pressures, and a whole host of other factors.

In this case, I chose to write

Blackbox tests designed for adequate coverage of MinimalAPI endpoints

Ensure your tests pass.

Deployment and Clients

Look for future articles on deploying the MinimalAPI to Azure using GitHub Actions as well as demo UI consuming this API, a web app configured through Swagger and OpenAPI to be a client.

Cleanup and Last Thoughts

Did you catch it? There’s a discrepancy between the tests and the Program.cs. What do you think it is?

And, for the practice, you may want to cleanup the API, removing all weather references. You’re already using source control, right?

CR Johnson

As a software engineer with over a decade of experience working for Fortune 50 companies developing software for Windows, the web, and a few interplanetary spacecraft, she's programmed in a plethora of languages including the C#/ASP.NET stack and, recently, Rails. She has tweaked more CSS files than she can count and geeks out a little on data and SQL databases. In her spare time she works on her first novel and enjoys bicycling and dark chocolate.