Microsoft Architect
By Joydip Kanjilal, Columnist, InfoWorld |
Take advantage of the built-in support for OpenAPI in ASP.NET Core to automatically document your HTTP endpoints. Minimal APIs are supported too.

ASP.NET Core 6 introduced a simplified hosting model that allows us to build lightweight APIs with minimal dependencies. These minimal API projects make it easy to get our application up and running fast, by writing less boilerplate code. ASP.NET Core 7 further improved minimal APIs by adding support for filters.
Whenever you work with APIs—including minimal APIs—you will often want to document your endpoints. Fortunately, ASP.NET Core provides built-in support for the OpenAPI specification, so you can take advantage of OpenAPI and the Swagger UI to generate nice documentation for all of your APIs.
The goal of this post is to give you a head start on doing so. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.
Create a minimal Web API project in Visual Studio 2022
First off, let’s create an ASP.NET Core project in Visual Studio 2022. Follow these steps:
- Launch the Visual Studio 2022 IDE.
- Click on “Create new project.”
- In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
- Click Next.
- In the “Configure your new project” window, specify the name and location for the new project.
- Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
- Click Next.
- In the “Additional Information” window shown next, uncheck the check box that says “Use controllers…” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” set as “None” (default). Check the “Configure for HTTPS” and “Enable Open API Support” check boxes. Finally, ensure that the “Enable Docker” check box is unchecked as we won’t be using Docker here. (See Figure 1 below.)
- Click Create.

We’ll use this ASP.NET Core 7 Web API project to use OpenAPI to document minimal API endpoints in the sections below.
What is the OpenAPI specification?
Previously known as the Swagger specification, the OpenAPI specification defines a standard, machine-readable, programming language-agnostic interface description language (IDL) for APIs. It is a language-independent standard for describing HTTP APIs. The standard is supported by a combination of built-in APIs and open-source libraries.
The three most significant aspects of OpenAPI integration in an application are:
- Creating information about the app’s endpoints.
- Putting the data together in a format compatible with the OpenAPI standard.
- Exposing the created OpenAPI schema through a graphical user interface or a serialized file.
Because we enabled OpenAPI support when we created our ASP.NET Core 7 Web API project, the Swashbuckle.AspNetCore package will be added to the project automatically. Swashbuckle is an open source project that enables the generation of Swagger documentation.
Note that you can always add the Swashbuckle.AspNetCore NuGet package to your other projects manually.
Create a simple minimal API endpoint in ASP.NET Core
When you create a new ASP.NET Core Web API project in Visual Studio, the default controller (named WeatherForecast) and model class will be created automatically. Because we’re using minimal APIs here, these files will not be created.
Instead, a default HTTP GET endpoint will be created in the Program.cs file. Now, replace the default generated code of the HTTP GET endpoint with the following code.
app.MapGet("/", () => "Hello World!").WithName("Welcome").WithOpenApi();
When you run the application, you’ll be able to see the Swagger UI in your web browser, as shown in Figure 2.

Configure Swagger in a minimal API in ASP.NET Core
The code snippet below illustrates how you can configure the Swagger middleware to add metadata for the API document.
builder.Services.AddSwaggerGen(setup => setup.SwaggerDoc("v1", new OpenApiInfo(){ Description = "This is a simple implementation of a Minimal Api in Asp.Net 7 Core", Title = "Demo Api", Version = "v1", Contact = new OpenApiContact() { Name = "Joydip Kanjilal", Url = new Uri("https://joydipkanjilal.com") }}));
When you execute the application now, the metadata you added will be displayed in the Swagger UI as shown in Figure 3.

Create a model class
Now let’s flesh out our minimal API example application. First, create a model class using the following code.
public class Author{ public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string Email { get; set; } public string Phone { get; set; }}
Create and implement an interface
Next, create an interface named IAuthorRepository and enter the following code.
public interface IAuthorRepository{ Author GetById(int id); void Create(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) { throw new NotImplementedException(); } Author IAuthorRepository.GetById(int id) { throw new NotImplementedException(); } void IAuthorRepository.Update(Author entity) { throw new NotImplementedException(); }}
Note that none of the methods of the AuthorRepository class have been implemented. We’ll use this skeleton implementation just for the purposes of seeing how we can work with OpenAPI in minimal API applications.
Create a minimal API endpoint
Lastly, delete the endpoint we created earlier since we won’t be needing it anymore. Instead, add the following piece of code to your Program.cs file to create four new endpoints.
app.MapGet("/authors/{id}", async ([FromServices] Author entity, int id) =>{ return Results.Ok();});app.MapPost("/authors", async ([FromServices] Author entity) =>{ return Results.Ok();});app.MapPut("/authors/{id}", async ([FromServices] int id, Author entityToUpdate) =>{ return Results.Ok();});app.MapDelete("/authors/{id}", async ([FromServices] int id) =>{ return Results.Ok();});
When you run the application, you should see these endpoints displayed in your Swagger UI as in Figure 4.

Complete minimal API example in ASP.NET Core
The complete code listing for our OpenAPI-documented minimal API is given below for your reference.
using Microsoft.AspNetCore.Mvc;using Microsoft.OpenApi.Models;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();builder.Services.AddSwaggerGen(setup => setup.SwaggerDoc("v1", new OpenApiInfo(){ Description = "This is a simple implementation of a Minimal Api in Asp.Net 7 Core", Title = "Demo Api", Version = "v1", Contact = new OpenApiContact() { Name = "Joydip Kanjilal", Url = new Uri("https://joydipkanjilal.com") }}));var app = builder.Build();// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI();}app.UseHttpsRedirection();app.MapGet("/authors/{id}", async ([FromServices] Author entity, int id) =>{ return Results.Ok();});app.MapPost("/authors", async ([FromServices] Author entity) =>{ return Results.Ok();});app.MapPut("/authors/{id}", async ([FromServices] int id, Author entityToUpdate) =>{ return Results.Ok();});app.MapDelete("/authors/{id}", async ([FromServices] int id) =>{ return Results.Ok();});app.Run();public class Author{ public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string Email { get; set; } public string Phone { get; set; }}public interface IAuthorRepository{ Author GetById(int id); void Create(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) { throw new NotImplementedException(); } Author IAuthorRepository.GetById(int id) { throw new NotImplementedException(); } void IAuthorRepository.Update(Author entity) { throw new NotImplementedException(); }}
By enabling OpenAPI support in your Web API projects when you create them, you can have ASP.NET Core automatically document your HTTP endpoints, and you can view that information through the Swagger UI. Note you can customize the Swagger UI using Cascading Style Sheets, show enum values as string values, and create different Swagger documents for different versions of your API.
Related:
- Microsoft .NET
- C#
- Software Development
- Web Development
- APIs
Joydip Kanjilal is a Microsoft MVP in ASP.Net, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .Net and related technologies.
Copyright © 2023 IDG Communications, Inc.
How to choose a low-code development platform
FAQs
How can I improve my NET Core application performance? ›
- Cache aggressively.
- Understand hot code paths.
- Avoid blocking calls.
- Return large collections across multiple smaller pages.
- Minimize large object allocations.
- Optimize data access and I/O.
- Pool HTTP connections with HttpClientFactory.
- Keep common code paths fast.
- Right-click the API project in Solution Explorer and select Manage NuGet Packages.
- Type Swashbuckle.AspNetCore in the search box.
- Select Swashbuckle.AspNetCore and click Install.
- From the File menu, select New > Project.
- Enter Web API in the search box.
- Select the ASP.NET Core Web API template and select Next.
- In the Configure your new project dialog, name the project TodoApi and select Next.
- In the Additional information dialog: Confirm the Framework is . NET 7.0 (or later).
Create an ASP.NET Core REST API application
Step 1: Go to File > New, and then select Project. Step 2: Choose Create a new project. Step 3: Select ASP.NET Core Web Application template. Step 4: Enter the Project name, and then click Create.
NET Core is faster than . NET Framework because the architecture of . NET Core is written or restructured from scratch to make it a modular, lightweight, fast, and cross-platform Framework. The Applications require technologies like workflow, webforms or WCF that are not present in .
Why is ASP.NET Core so fast? ›NET Core is faster for working with more modern libraries and programming languages. It is more lightweight and modular than . NET Framework, and you can use multiple versions of . NET in the same project.
Is .NET core good for API? ›ASP.NET Core supports creating web APIs using controllers or using minimal APIs. Controllers in a web API are classes that derive from ControllerBase.
What is OpenAPI vs Swagger? ›OpenAPI is a specification that can be used with any format, including REST, JSON-RPC, and SOAP. In contrast, Swagger tools are specifically designed to work with REST APIs that use JSON or YAML for the request and response bodies. Overall, OpenAPI and Swagger are both valuable tools for API development.
What is OpenAPI in net core? ›NET Core. OpenAPI is a specification for describing RESTful APIs. First, I'll show you how to use OpenAPI to describe the APIs provided by an ASP.NET Core service. Then, we'll use the API description to generate a strongly-typed client to use the web service with C#.
What is the difference between .NET Core web API and REST API? ›3) Web API vs REST API: Design
As Web APIs are lightweight architecture, they are designed for gadgets constrained to devices like smartphones. In contrast, REST APIs send and receive data over systems making it a complex architecture.
How to fetch data from API in dotnet core? ›
- Define your PokeItem model. ...
- here will be aUsing Directive. ...
- Define your GetPokemon Method. ...
- Get the response, and data from the response. ...
- Log data to your console. ...
- Get Pokemon Method.
In ASP.NET Core, there's no longer any distinction between MVC and Web APIs. There's only ASP.NET Core, which includes support for view-based scenarios, API endpoints, Razor Pages, health checks, SignalR, and more. In addition to being consistent and unified within ASP.NET Core, APIs built in .
What is API and why we are using API with .NET Core? ›In simple words, we can say that a web API is an application programming interface for a web application or web server. It uses HTTP protocol to communicate between clients and websites to have data access. Asp.net Core web API is a cross-platform web API.
How to use JWT in ASP.NET Core? ›- Create a minimal API project in Visual Studio 2022.
- Create an API endpoint in the Program.cs file.
- Add the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package to our project.
- Implement JWT authentication in the Program.cs file.
- It works the way HTTP works, using standard HTTP verbs like GET, POST, PUT, DELETE for all CRUD operations.
- Full support for routing.
- Response is generated in JSON and XML format using MediaTypeFormatter.
- It can be hosted on IIS as well as auto-hosted outside of IIS.
NET Core has an easier time working with CPU-intensive tasks and rendering static pages since the in-built IIS server kernel caching makes this process very straightforward. Therefore, . NET core vs node.
What are the limitations of .NET Core? ›You cannot use Windows-specific APIs in ASP.NET Core and . NET Core since these frameworks are designed to be more independent from the operating system. For example, you cannot use System.
What are the disadvantages of .NET Core? ›ASP.NET Core Cons
It will take a few years till existing products based on . NET Core will be fully updated. Though there are a lot of . NET developers on the market, ASP.NET Core framework is a huge step forward comparing to ASP.NET Framework and there are many changes and new concepts.
It is still widely used by developers and remains a top open-source framework on GitHub. In fact, according to the Stack Overflow 2021 developer survey, more than 15% of developers still prefer ASP.NET over other frameworks for their web development needs.
Is ASP.NET Core dead? ›Microsoft to End Support for . NET Core 3.1 in December 2022.
Is .NET Core going away? ›
Note: The . NET 5.0 SDK versions will continue to be supported in VS 16.11 until December of 2022 when . NET Core 3.1 goes out of support so that . NET Core 3.1 customers can continue to use 16.11 to developer their applications.
When should you not use .NET Core? ›- Windows Forms and WPF applications are not supported – You still have to use Mono to make a . ...
- ASP.NET WebForms don't exist – Though Microsoft provides strategies for migrating ASP.NET Web Forms apps.
- You need to create a WCF service – . ...
- Missing 3rd-party library support – . ...
- Missing .
NET Core and . NET Framework. ASP.NET Core is the best framework for building microservices applications because it offers incredible benefits including cloud-based configurations, rapid development, and cross-platform support.
What is the best test framework for .NET Core? ›xUnit.net – Recommended
For example, when running xUnit tests, the class containing the test methods is instantiated separately for each test so that tests cannot share data and can run in parallel. xUnit.net is currently the most popular framework - and is even used by the . NET Core team.
JsonAPI, Postman, GraphQL, OData, and RAML are the most popular alternatives and competitors to OpenAPI.
Is OpenAPI rest or RPC? ›OpenAPI is a language for describing REST APIs.
It's a structured way of describing REST APIs using JSON or YAML that was originally created to better document APIs.
REST APIs use HTTP protocol for data transmission. This protocol allows platforms and systems written in different programming languages to interact. OpenAPI deals with RESTful APIs only, not other types of APIs.
How do I use Swagger with OpenAPI? ›- Go to Swagger Inspector. ...
- Make calls to your API. ...
- Select requests in the History and create API definition. ...
- Follow the prompts to go to SwaggerHub.
- Name your API. ...
- Your definition is there!
The OpenAPI Specification is a standard format to define structure and syntax REST APIs. OpenAPI documents are both machine and human-readable, which enables anyone to easily determine how each API works. Engineers building APIs can use APIs to plan and design servers, generate code, and implement contract testing.
What is the point of OpenAPI? ›Single point of truth
An OpenAPI definition is machine-readable and serves as the single source of truth for the API. This allows the import of API definitions into clients for manual testing and ensures each piece of the system can be verified against the specification.
Which API Gateway is best for microservices .NET Core? ›
Ocelot is an Open Source . NET Core-based API Gateway especially made for microservices architectures that need unified points of entry into their systems. It's lightweight, fast, and scalable and provides routing and authentication among many other features.
Which is better than REST API? ›GraphQL is a query language and is increasingly seen as a more efficient, flexible and powerful way of working with APIs than REST. APIs are a set of rules that allow software programs to talk with each other, and they are a pivotal piece of software technology today, especially for headless CMS platforms.
What is OData in .NET Core Web API? ›OData is defined as "An open protocol to allow the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way" (odata.org). You can use OData with ASP.NET Boilerplate. The Abp. AspNetCore.
How do I get responses from API in .NET Core? ›- Creating a Database for Our Project.
- Basic Code Preparations.
- Logging with NLog in ASP.NET Core.
- Repository Pattern with Entity Framework Core.
- Using Repository for GET Requests (Current article)
- Using Repository for POST, PUT and DELETE Requests.
- Configure the API endpoint. An API endpoint can be complex. ...
- Create an API resource. ...
- Store data into a database. ...
- Transform the API data. ...
- Export the data to an application. ...
- Check and maintain the pipeline.
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
What are the 4 main types of Web APIs? ›Four types of web APIs
There are four different types of APIs commonly used in web services: public, partner, private and composite. In this context, the API "type" indicates the intended scope of use.
The Kestrel web server is Microsoft's cross-platform HTTP server framework for ASP.NET Core runtime support. Kestrel runs on both Windows and Linux hardware to provide standardized compilation support for ASP.NET applications in production. In basic terms: Kestrel is the default web server for ASP.NET Core hosting.
What are the three types of APIs available? ›- REST, a collection of guidelines for lightweight, scalable web APIs.
- SOAP, a stricter protocol for more secure APIs.
- RPC, a protocol for invoking processes that can be written with XML (XML-RPC) or JSON (JSON-RPC).
- static void Main(string[] args)
- {
- using var client = new HttpClient();
- client. BaseAddress = new Uri(url);
- // Add an Accept header for JSON format.
- client. DefaultRequestHeaders. Accept. Add(
- new MediaTypeWithQualityHeaderValue("application/json"));
- // Get data response.
What are two benefits of using API? ›
When using an API managed by computers, less human effort is required and workflows can be easily updated to become faster and more productive. Furthermore, new content and information can be published and shared with your entire audience quickly and efficiently across all channels.
How to get data from Web API in C#? ›...
Click on "Generate from Database".
- Click on "New Connection".
- Enter your server name.
- Choose your authentication, here we use the SQL Server Authentication, then we enter the user name and password.
- Select your database.
- The JWT specification is specifically designed only for very short-live tokens (~5 minute or less). ...
- JWTs which just store a simple session token are inefficient and less flexible than a regular session cookie, and don't gain you any advantage.
JWT is commonly used mechanism for client request authentication and provides identity of authenticated users between identity provider and service provider. Where as secure socket layer provides secure connection between two parties that is client and server.
Which authentication is best for Web API? ›OAuth (specifically, OAuth 2.0) is considered a gold standard when it comes to REST API authentication, especially in enterprise scenarios involving sophisticated web and mobile applications. OAuth 2.0 can support dynamic collections of users, permission levels, scope parameters and data types.
Which architecture is best for .NET Core? ›ASP.NET Core's built-in use of and support for dependency injection makes this architecture the most appropriate way to structure non-trivial monolithic applications. For monolithic applications, the Application Core, Infrastructure, and UI projects are all run as a single application.
How do I add swagger to .NET Core API? ›Add and configure Swagger middleware
Launch the app and navigate to https://localhost:<port>/swagger/v1/swagger.json . The generated document describing the endpoints appears as shown in OpenAPI specification (openapi. json). The Swagger UI can be found at https://localhost:<port>/swagger .
- Minimize virtual calls. ...
- Pool HTTP connections. ...
- Reduce allocations. ...
- Cache aggressively. ...
- Enable compression. ...
- Reduce HTTP requests. ...
- Avoid blocking calls. ...
- Minimize large object allocations.
- Every developer should use a profiler. ...
- The higher the level, the slower the speed (usually) ...
- Don't underestimate release builds vs. ...
- Look at the bigger picture. ...
- Memory locality matters. ...
- Relieve the pressure on the garbage collector. ...
- Don't use empty destructors.
One of the best ways to improve API performance is by caching to serve content faster. If there are concurrent requests frequently producing the same response, then the response can be cached to avoid excessive database queries and provide quick access.
How do I test .NET application performance? ›
In the Windows Performance Monitor (Perfmon.exe), the per-application counters are available under the ASP.NET Applications performance object. If there are multiple applications on the server, you specify a particular application instance when selecting a counter to monitor.
How many requests can asp net core handle? ›Assuming you are using Kestrel as the underlying web server the default number of concurrent connections in ASP.NET Core 2.2 is defined as unlimited.
What increases server utilization? ›Increase server utilisation
The commonest way to improve server utilisation is to virtualise the box using, for example, VMware or Xen. This allows you to take say a 32 x core server and create a number of smaller “virtual” servers, each with its own operating system.
Sync is single-thread, so only one operation or program will run at a time. Async is non-blocking, which means it will send multiple requests to a server. Sync is blocking — it will only send the server one request at a time and will wait for that request to be answered by the server.
Which loop is faster in C#? ›The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
How to increase page loading speed in asp net core? ›- Upgrade all the libraries and the framework. .NET Framework. ...
- Optimize images. Use the new image formats. ...
- Bundle and minify your files. CSS and Javascript files. ...
- Remove unused CSS.
- Content Delivery Network.
- ASP.NET Caching. Response Caching Middleware. ...
- Response Compression.
As a compiled language, C# converts directly into machine code that a processor can execute. No interpreter needed. In some cases, this means that C# code can run up to 44 times faster than Python. And whilst you can speed up Python's performance significantly with PyPy's JIT compiler, C# still holds its lead here.
How do you handle millions of API requests? ›To handle 'millions of request' the system must be deployed on multiple web servers behind a load-balancer that would round robin between each. if the system is hitting a datastore, a second level cache(ehcache, memcache,etc.) should be used to reduce load on the datastore.
What are the 3 principles for a RESTful API? ›- Uniform interface. ...
- Client-server decoupling. ...
- Statelessness. ...
- Cacheability. ...
- Layered system architecture. ...
- Code on demand (optional).
- Client-server architecture. An API's job is to connect two pieces of software without limiting their own functionalities. ...
- Statelessness. ...
- Uniform Interface. ...
- Layered system. ...
- Cacheability. ...
- Code on Demand.
What is the best .NET performance profiler? ›
Some of the most popular performance profilers are dotTrace, ANTS performance profiler, and Visual Studio profiling tools.
How would you diagnose the poor performance from a .NET application? ›You can detect these types of performance problems by running load tests that simulate production-level traffic on your development-stage applications. By identifying issues before deployment, you can fix bottlenecks before they're ever experienced by production users.
How do you manually test a web application? ›- Analyze requirements from the software requirement specification document.
- Create a clear test plan.
- Write test cases that cover all the requirements defined in the document.
- Get test cases reviewed by the QA lead.
- Execute test cases and detect any bugs.