In this tutorial we will learn how to create a RESTful API using the .NET platform. The process is quite straightforward and much of the complexity is already baked in to the starter template we will use. In a follow up tutorial series, we will create a NuGet package that will wrap the action routes with an automatically generated client so that it can be easily shared to complement the API.
Why OpenAPI?
The OpenAPI specification provides a consistent means to carry information through each state of the API lifecycle. It defines structure and syntax in a way that is not coupled to the programming language the API was created in. More importantly, this specification allows developer tools to automate and abstract away much of the complexity invovled in consuming APIs.
The below text will expose multiple tools available to beginners and amateurs so that they may speed up their delivery time and grasp an understanding of where the industry is headed. We will be using the command line and VSCode to avoid any unnecessary complexity.
Step 0: Make sure dotnet
is installed in your machine
If you are unsure if dotnet
is installed in your machine go ahead and open your command line and type the following:
dotnet --version
If you receive an error it means that you have not installed the dotnet
tools or if you have, it is not part of your working path. The instructions for adding the dotnet
executable to your working path differ by operating system but the concept remains the same; you can follow this post for Windows and this post for MacOS.
You will need to use .NET 6+ to follow along with this tutorial.
Step 1: Create a folder for the solution and project
Using your command line, go ahead and navigate to the folder where you will place your solution. Afterwards, create a new folder to house your solution, likeso:
mkdir QuickAPI
cd QuickAPI/
Next, you want to create the solution file that will contain your various projects. If you aren't familiar with the concept of a .sln
file I recommend reading the following excerpt: Learn Microsoft: Solution file. In summary, .sln is a text-based file that contains information about the environment of a project(s) and it's hierarchy of dependencies.
dotnet new sln
Lastly, we want to create the web API using the default template provided by the .NET framework. Within your solution directory go ahead and create a new folder and give it the name of your project. For this example we will call our project API
. This template project already has much of the tooling we will extend to make our code accesible to third-parties via the HTTP protocol.
mkdir API
cd API
dotnet new webapi
At this point you can run the project with the below command. You should see a URL in the console output that you can use to navigate to the API with any browser on your machine. If this is the first time you are running the project locally over https you will have to trust a self-signed certificate. Luckily for us, that is also included within the .NET framework.
dotnet dev-certs https --trust
dotnet run -lp https
Step 2: Create and modify HomeController.cs file
If you visit the URL displayed on the console output you will most likely end up in an empty page. So what's the deal?
You will have to append /swagger/index.html
at the end of the URL to pull up the user interface auto-generated by Swagger (commonly known as SwaggerUI). This is kind of annoying and can be easily fixed by adding a redirect so you will always land on this page. I highly recommend this is you are new to .NET.
Go ahead and create a new controller and name it HomeController.cs
. Add a public method named Index
like below. This will serve as our applications entry point. Now, whenever you visit the base URL of your application you will always be redirected to the Swagger interface.
public class HomeController : ControllerBase
{
[Route(""), HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public RedirectResult Index()
{
return Redirect("/swagger/index.html");
}
}
You will notice that we have added a few attributes to our method which provide a powerful method of associating metadata, or declarative information, with code.
Step 3: Run project and validate Swagger
Now we can finally move on to the fun stuff which is making calls to our API. The user interface provided by Swagger has all sorts of cool stuff. You can directly call the API endpoints as well as view and download server response. First, make sure you are within the context of your project folder, then run the below command to fire up your API. Your command line output should have the localhost address you can navigate to in the browser of your choice.
dotnet run
Step 4: Swagger UI analysis
There are a few components we can now analyze in the UI. First off, you'll notice that any controller you create will be added to it's own section (as was WeatherForecast
). Under each controller section you will see the RESTful endpoints (i.e. class methods) that you choose to expose with their corresponding actionable verb (GET/POST/PUT/DELETE). Lastly, any class definitions used by your controllers will be exposed under the Schemas section where you can view their properties and property types.
Conclusion
With this you have created your very own RESTful API in accordance to the OpenAPI specifications. While this tutorial was nothing novel it will help us move forward with more complex topics in a later series. For now, feel free to play around and discover everything that .NET has to offer.