We’re continuing our series on building HTTP APIs with .NET 5. In the previous post, we covered Creating Discoverable HTTP APIs with ASP.NET Core 5 Web API. In this post, we’ll go further with a look at using open-source HTTP API packages and tools. Let’s dig in!
- Creating Discoverable HTTP APIs with ASP.NET Core 5 Web API
- Open-source HTTP API packages and tools (this post)
- Generating HTTP API clients using Visual Studio Connected Services
- App Building with Azure API Management, Power Apps, and Logic Apps
Open-source tools, packages, and extensions for HTTP API developers
This post will cover a variety of things any .NET developer who plans on building HTTP APIs will want in their toolchain or dependency list. We’ll show you some new and exciting frameworks coming up that are built atop ASP.NET Core web API and hopefully make the craft of building and testing HTTP APIs with .NET easier. There are so many opportunities in the form of NuGet packages, Visual Studio and Visual Studio Code extensions, and independently-maintained frameworks, we can’t capture them all in one post. Feel free to use the comments below to share some of your favorite web API tools and packages.
NuGet packages for building .NET HTTP APIs
This first section will cover some of the most important NuGet packages in your HTTP API toolchain. Many of these tools are used in our own pet projects and workshops. Some of the tools appear in our templates and tools as dependencies.
OpenAPI generation
In the first article in this series, we touched on the idea of creating discoverable APIs. Since the term discoverable in API lingo is associated with service discovery, maybe the better term for the article would have been well-described. By describing APIs using the OpenAPI specification (formerly Swagger specification), developers get all kinds of code-generation and integration opportunities. We’ll touch on those later in the series. The point is that OpenAPI generation is important and should be something you’re at least generating, if not designing.
Some consider the idea of generating OpenAPI specifications from code an “inside-out” approach, and design tools are a topic we’ll touch on later. But when building quickly, or maintaining a level of “well-designedness” whilst still generating the specification from code, you have two main options with traditional ASP.NET and ASP.NET Core web API: NSwag and Swashbuckle. Both of these projects are maintained almost entirely by single individuals with small teams of passionate contributors, and both have had a signifcant impact in the .NET HTTP API ecosystem.
NSwag
Whilst NSwag’s most popular usage scenario is OpenAPI specification generation from web API controller projects via NSwag.AspNetCore, the project’s team has contributed all manner of other contributions:
- Code generation to generate strongly-typed C# HTTP API clients, Web API Controllers from OpenAPI, and TypeScript clients.
- Build OpenAPI specifications from existing .NET assemblies. For example, binaries, not source.
- A desktop app, NSwagStudio, that allows you to utilize most of the NSwag features without having to write code.
NSwag’s rich ecosystem of NuGet packages is used by the Visual Studio Connected Services “OpenAPI SDK Generation” feature, which we’ll explore in more detail in the third article in this series. NSwag’s code generation tools produce quality, idiomatic C# client code for well-described APIs.
Swashbuckle
Swashbuckle has been used by millions of web API projects built by customers and internal teams. It was also adopted by the Swagger Codegen team in their templates, which are used by many API ecosystem products. Given the presence Swashbuckle has in the web API space, it has been used in our templates since the .NET 5 RC release. It is on-by-default but can be toggled in the new project dialog in Visual Studio (or using the --no-openapi
option with the .NET CLI’s dotnet new webapi
command).
Swashbuckle also has a .NET CLI tool, Swashbuckle.CLI, that can be used to generate OpenAPI specifications during your MSBuild or dotnet publish
commands. The sample project has an example C# project file showing how to use the Swashbuckle CLI during a build process.
Microsoft.OpenAPI
No list of important NuGet packages for the HTTP API developer ecosystem would be complete without Microsoft.OpenAPI. A dependency of most of the OpenAPI-supporting projects in the .NET and Azure community, this package is responsible for a variety of features:
- Translating between versions of Swagger and OpenAPI, YAML, or JSON flavors.
- Provides a single shared object model in .NET for OpenAPI descriptions.
- Reading and writing OpenAPI descriptions.
If you’re building an app or NuGet package for .NET HTTP API developers using OpenAPI, you’ll probably want to take a look at Microsoft.OpenAPI
. It will ease much of the burden of parsing or writing OpenAPI documents and descriptions.
ASP.NET API Versioning
One of the most important concepts in building APIs that no one tells you about until too late is that, at some point, you’ll need to release breaking changes in APIs many of your customers continue to use. Versioning APIs is complex, and it doesn’t help when you have to do everything manually, so having a fantastic (and used by so many customers and internal teams I’d argue prolific), is ASP.NET API Versioning. Scott Hanselman wrote about API Versioning way back in 2016, and since then it has become an important asset in web API development.
API Versioning enables you to decorate your API controllers with additional attributes that enable the API versions in which the controller’s operations should appear.
[ApiVersion("1.0")]
[ApiVersion("1.1")]
public class ShopController : ControllerBase
{
}
Controller action methods can be decorated as well, to identify the versions in which they map or “appear.” In the sample code complementing this series, you’ll see the GetProducts
method and the GetProductsPage
method, added in version 1.1 of the API.
[HttpGet("/products", Name = nameof(GetProducts))]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await Task.FromResult(Ok(StoreServices.GetProducts()));
}
[HttpGet("/products/page/{page}", Name = nameof(GetProductsPage))]
[MapToApiVersion("1.1")]
public async Task<ActionResult<IEnumerable<Product>>> GetProductsPage([FromRoute] int page = 0)
{
var pageSize = 5;
var productsPage = StoreServices.GetProducts().Skip(page * pageSize).Take(pageSize);
return await Task.FromResult(Ok(productsPage));
}
API Versioning has many samples and Wiki articles on how to get started. One of these shows how to use API Versioning and Swashbuckle together, which I’ve borrowed for the sample project accompanying this blog series. By adding a small amount of additional code to Startup.cs
and by using a few infrastructure classes to iterate over the various API versions in your project, you can enlist API Versioning to help you draw out independent Swagger UI pages for multiple versions of your APIs. This changes the Swagger UI to show a drop-down menu containing the API versions in your project.
Note the Shop
operations—there are 3 in the 1.0
version of the API. But once we change the version menu to see the 1.1
, the new GetProductsPage
operation only available in the 1.1
API version appears.
The code generation tools in Visual Studio Connected Services OpenAPI SDK generation features are aware of the api-version
querystring that the API will expect now. When using API Versioning, the generated code adds a parameter to capture the API version string, too. This can be defaulted so that API Versioning will automatically pick the intended version, but in this case I’m implying a more opinionated approach with my client.
// create a product
apiClient.CreateProductAsync("1.1",
new CreateProductRequest
{
Id = 1000,
InventoryCount = 0,
Name = "Mild Salsa"
});
// update a product's inventory
apiClient.UpdateProductInventoryAsync(1000, "1.1",
new InventoryUpdateRequest
{
CountToAdd = 50,
ProductId = 1000
});
Refit
Refit is the automatic type-safe REST library for .NET. It turns your interface into a live REST client. Consider the IContosoOnlineOrdersApiClient
example interface below, which would expose method signatures for calling a few of the API methods.
public interface IContosoOnlineOrdersApiClient
{
[Get("/products")]
Task<IEnumerable<Product>> GetProducts();
[Post("/products")]
Task CreateProduct([Body] CreateProductRequest request);
}
Refit’s RestService
class generates an implementation of IContosoOnlineOrdersApiClient
that uses HttpClient
to make its calls. In the example solution, there’s a Refit client project demonstrating how to use a Refit client to access a back-end HTTP API.
var client = RestService.For<IContosoOnlineOrdersApiClient>("http://localhost:5000");
var products = await client.GetProducts();
await client.CreateProduct(new CreateProductRequest
{
Id = 1001,
InventoryCount = 10,
Name = "Taco Shells"
});
products = await client.GetProducts();
If you’re hand-rolling your own client code for back-end APIs, Refit is a great option you should investigate. Refit enables a simplified approach to creating clients for HTTP APIs and abstracts away all of the nuanced HttpClient
semantics.
Tools and extensions for designing and testing HTTP APIs
In addition to these useful NuGet packages, there are a handful of great tools you can use from both the command line and within your favorite IDEs for designing, building, and testing HTTP APIs.
The HttpRepl
The HttpRepl is a .NET CLI Global tool that can be that provides a directory-style way of exploring an HTTP API described by an OpenAPI specification. Once installed, you can use the command httprepl -o <openapi-url>
to connect to any OpenAPI-described web API project and explore it using familiar commands like ls
or dir
and navigating the API’s structure much like a directory tree.
If you haven’t tried the HttpRepl, check out the HttpRepl docs for more information on the various commands it offers. The docs also show how you can set up the HttpRepl as a “browser” so you can “F5 debug into the HttpRepl” if you’re more comfortable in the terminal.
REST Client for Visual Studio Code
There are some impressive HTTP API tools that ship as extensions to Visual Studio Code. One of these, REST Client, offers in-IDE HTTP API request testing. By creating .http
files into which you write your own request tests, you can trigger REST Client to activate “Send Request” links above each HTTP request you intend on testing.
Network Console
Microsoft Edge DevTools recently included an experimental feature named Network Console. Network Console offers Edge users in-browser HTTP API testing features. To try it out you’ll first need to enable the Network Console in Edge DevTools experimental features.
Once Network Console is enabled, you can right-click any previously made HTTP request and select the Edit and Resend menu item.
Clicking Edit and Resend will open an HTTP API testing tool, right inside of Edge. So, when you’re building web apps that make HTTP API calls back to the server, or when you’re building Blazor apps that do this sort of thing, you can resend the messages and analyze the API behavior without leaving your browser.
OpenAPI Editor
Editing or manually-creating OpenAPI documents can be daunting, so it helps when you can install a great editor and OpenAPI design extension right into Visual Studio Code. OpenAPI Editor provides just such functionality. This extension includes features like:
- Swagger UI and ReDoc preview
- IntelliSense for when you’re manually editing the JSON/YAML content for your OpenAPI specification
- Navigation in the form of tool windows inside of Visual Studio Code.
I can use the tool window to find an individual operation in my HTTP API rather than scrolling through a huge JSON file.
Frameworks built atop ASP.NET Core or Web API
With such a vibrant community, it’s common for open-source contributors to extend the ASP.NET framework with their own inventions, or even to push web API into new and exciting directions. Two recent projects are great examples of how the community is taking ASP.NET and web API in new directions.
API Endpoints
Steve Smith has started working on an exciting project known as API Endpoints that builds on top of ASP.NET Core web API. The project has a mission of abstracting away the need for a developer to think about the concept of a controller to build their HTTP API. Steve wrote about API Endpoints on his blog, describing his aspirations and the direction of the project. Essentially, API Endpoints abstracts the controller away so you’re left with a bit less code to author, whilst still being able to use the full feature-set provided by ASP.NET Core MVC Action Result classes.
[HttpPost("/authors")]
[SwaggerOperation(
Summary = "Creates a new Author",
Description = "Creates a new Author",
OperationId = "Author.Create",
Tags = new[] { "AuthorEndpoint" })
]
public override async Task<ActionResult<CreateAuthorResult>> HandleAsync([FromBody]CreateAuthorCommand request)
{
var author = new Author();
_mapper.Map(request, author);
await _repository.AddAsync(author);
var result = _mapper.Map<CreateAuthorResult>(author);
return Ok(result);
}
Since API Endpoint sits atop web API, you can use Swashbuckle or NSwag, or any other web API extension along with API Endpoints and reap the benefits of the wider web API stack, but taking a more modular approach rather than one based on MVC.
The Carter Project
The Carter Community’s Carter project brings even more modularity to your ASP.NET Core apps. Inspired by the Nancy project, Carter brings an endpoint-centric approach to building HTTP APIs with ASP.NET Core. The syntax for Carter is great for developers who appreciate the endpoint routing approach, and offers a clean set of APIs for getting started quickly.
public class HomeModule : CarterModule
{
public HomeModule()
{
Get("/", async (req, res) => await res.WriteAsync("Hello from Carter!"));
}
}
With numerous samples and docs, the project is easy to learn and to experiment with, and offers an interesting spin on building HTTP apps. OpenAPI is built into Carter by default, so endpoints you create can be output to OpenAPI specifications automatically. Carter can also be intertwined with traditional web API and ASP.NET Core app structure, so you can use Carter along with familiar ASP.NET Core middleware and services.
Summary
APIs are about making our apps more open to change and to interaction with other APIs, apps, and services. There are many open-source and even more third-party tools, services, and frameworks built atop ASP.NET and ASP.NET Core web API to enable you limitless extension opportunities. The packages and tools listed in this post are just a few of the ones we use in our own projects and experiments, whilst others mark new directions in ASP.NET and our community’s approach to building software.
We hope this and the other posts in this series bring inspiration and delight to your API development experience. Use the comments below to share other tools, extensions, or packages you feel would augment this post.
Hi Just launched Thunder Client – GUI based Http Client extension for VS Code
https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client
Please download the extension and share any feedback
kooo
mmmm
kokos
this comment has been deleted.
this comment has been deleted.
this comment has been deleted.
this comment has been deleted.
this comment has been deleted.
this comment has been deleted.
this comment has been deleted.
Great article with nice and short examples. I would suggest another great library for creating robust ASP.NET Core WebAPI: AspNetCoreRateLimit
Thanks Brady
Thanks for the nice article! The link to the VSCode REST client does not work for me and result in a 404. Removing query parameter ‘WT.mc_id’ have it work as expected.
Wow there were a few of those. Thanks for the QA and ping, all fixed now.
In addition to NSwag you can also use NSwag-based Visual Studio extension to generate client code in a more convenient way than through NSwag Studio.
I would like to suggest another library: RestEase
As the author says, is heavily inspired on Refit, but more extensible, and that’s why I prefer it and always recommend it, too.
Oh wow that’s cool, too. Thanks for sharing, will look into this.
ASP.NET Core API Boxed is an ASP.NET Core project template which has Open API using Swashbuckle, API Versioning and a lot more pre-configured and ready to go. Creating a project is as simple as running:
Oh I like this a lot. What do folks think of a project template with EVERYTHING in it like this, though? Not too much? Thanks for sharing, I love this. Will install and tinker around.