ASP.NET Core 6 presented a streamlined hosting model that enables us to develop lightweight APIs with minimal dependencies. These minimal API jobs make it simple to get our application up and running quick, by writing less boilerplate code. ASP.NET Core 7 more enhanced minimal APIs by adding assistance for filters.
Whenever you deal with APIs– consisting of very little APIs– you will often wish to record your endpoints. Luckily, ASP.NET Core offers integrated support for the OpenAPI specification, so you can take advantage of OpenAPI and the Swagger UI to create nice documentation for all of your APIs.The goal of this post is to give you a running start on doing so. To utilize the code examples supplied in this article, you need to have Visual Studio 2022 Sneak peek set up in your system. If you do not currently have a copy, you can download Visual Studio 2022 here.
Develop a minimal Web API task in Visual Studio 2022
First off, let’s develop an ASP.NET Core 7 task in Visual Studio 2022. Follow these steps:
- Introduce the Visual Studio 2022 Sneak Peek IDE.
- Click “Produce brand-new task.”
- In the “Produce new project” window, select “ASP.NET Core Web API” from the list of design templates displayed.
- Click Next.
- In the “Configure your new project” window, define the name and place for the brand-new task.
- Additionally check the “Place solution and project in the same directory site” check box, depending on your choices.
- Click Next.
- In the “Additional Details” window revealed next, uncheck the check box that states “Use controllers …” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” set as “None” (default). Inspect the “Configure for HTTPS” and “Enable Open API Assistance” check boxes. Finally, make sure that the “Enable Docker” check box is unchecked as we will not be using Docker here. (See Figure 1 below.)
- Click Develop.
IDG Figure 1. Inspect the Configure for HTTP and Enable OpenAPI Assistance check boxes.
Leave Authentication set to None and the other check boxes unchecked. We’ll use this ASP.NET Core 7 Web API job to use OpenAPI to record very little API endpoints in the sections below.What is the OpenAPI specification?Previously referred to as
the Swagger spec, the OpenAPI spec defines a basic, machine-readable, configuring language-agnostic interface description language (IDL) for APIs. It is a language-independent standard for explaining HTTP APIs. The requirement is supported by a combination of integrated APIs and open-source libraries.
The 3 most significant aspects of OpenAPI combination in an application are:
- Producing information about the app’s endpoints.
- Putting the information together in a format compatible with the OpenAPI standard.
- Exposing the produced OpenAPI schema through a visual user interface or a serialized file.
Because we made it possible for OpenAPI support when we produced our ASP.NET Core 7 Web API job, the Swashbuckle.AspNetCore package will be added to the project immediately. Swashbuckle is an open source job that allows the generation of Swagger documents.
Note that you can always add the Swashbuckle.AspNetCore NuGet bundle to your other jobs manually.Create a basic very little API endpoint in ASP.NET Core When you develop a new ASP.NET Core Web API task in Visual Studio, the default controller(named WeatherForecast )and model class will be created automatically. Since we’re using minimal APIs here, these files will not be created.Instead, a default HTTP GET endpoint will be developed in the Program.cs file.
Now, replace the default generated code of the HTTP GET endpoint with the following code.app.MapGet(“/”,()= >”Hey there World!”). WithName(“Welcome “). WithOpenApi(); When you run the application, you’ll have the ability to see the Swagger UI in your web internet browser, as shown in Figure 2. IDG Figure 2. The Swagger UI. Set up Swagger in a
minimal API in ASP.NET Core The code
bit listed below illustrates how you can configure the Swagger middleware to include metadata for the API document.builder.Services.AddSwaggerGen(setup=> setup.SwaggerDoc(“v1”, brand-new OpenApiInfo() )); When you execute the application now, the metadata you included will be displayed in the Swagger UI as displayed in Figure 3. IDG
Figure 3. Including API metadata.
Produce a model class
Now let’s flesh out our minimal API example application. First, create a design class utilizing the following code.public class
Author public int Id public string FirstName public string LastName get; set; public string Address public string Email get; set; public string Phone
Produce and carry out a user interface
Next, produce a user interface called IAuthorRepository and enter the following code.
public user interface IAuthorRepository Author GetById(int id); space Develop(Author entity); void Delete(Author entity); void Update(Author entity);
Now create another class named AuthorRepository and enter the following code.public class
AuthorRepository: IAuthorRepository void IAuthorRepository.Create(Author entity) throw new NotImplementedException(); void IAuthorRepository.Delete(Author entity) Author IAuthorRepository.GetById(int id) toss new NotImplementedException(); void IAuthorRepository.Update(Author entity)
Note that none of the techniques of the AuthorRepository class have actually been implemented. We’ll utilize this skeleton execution simply for the functions of seeing how we can work with OpenAPI in very little API applications.Create a minimal API endpoint Lastly, delete the endpoint
we created earlier since we will not be needing it any longer. Instead, add the following piece of code to your Program.cs file to develop four brand-new endpoints.app.MapGet(“/ authors/ p>id”, async([ FromServices] Author entity, int id)=> .); app.MapPost(“/ authors”, async ([ FromServices] Author entity) => return Results.Ok(); ); app.MapPut(“/ authors/ “, async ([ FromServices] int id, Author entityToUpdate) => return Results.Ok(); ); app.MapDelete(“/ authors/ id “, async ([ FromServices] int id) => );
When you run the application, you must see these endpoints displayed in your Swagger UI as in Figure 4.
The four endpoints of our very little API. Complete very little API example in ASP.NET Core The total code listing for our OpenAPI-documented very little API is provided below for your reference.using Microsoft.AspNetCore.Mvc; utilizing Microsoft.OpenApi.Models; var contractor=WebApplication.CreateBuilder(args);// Add services to the container. builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(setup=> setup.SwaggerDoc(“v1”, brand-new OpenApiInfo() )); var app = builder.Build();// Set up the HTTP request pipeline. if (app.Environment.IsDevelopment()) app.UseHttpsRedirection(); app.MapGet(“/ authors/ “, async ([ FromServices] Author entity, int id) => ); app.MapPost(“/ authors”, async ([ FromServices] Author entity) => return Results.Ok(); ); app.MapPut(“/ authors/ “, async ([ FromServices] int id, Author entityToUpdate) => ); app.MapDelete(“/ authors/ id “, async ([ FromServices] int id) => ); app.Run(); public class Author public user interface IAuthorRepository Author GetById(int id); void Develop(Author entity); void Delete(Author entity); void Update(Author entity); public class AuthorRepository: IAuthorRepository void IAuthorRepository.Create(Author entity) throw new NotImplementedException(); void IAuthorRepository.Delete(Author entity) Author IAuthorRepository.GetById(int id) void IAuthorRepository.Update(Author entity) throw new NotImplementedException();
By allowing OpenAPI support in your Web API projects when you create them, you can have ASP.NET Core automatically record your HTTP endpoints, and you can view that info through the Swagger UI. Note you can personalize the Swagger UI utilizing Cascading Style Sheets, show enum worths as string values, and produce different Swagger files for different versions of your API.
Copyright © 2023 IDG Communications, Inc.