How to create ASP.Net Minimal APIs and deploy using Azure API Management

In this blog post we will understand what minimal APIs are and create a minimal web API project in ASP.Net Core 7.0. We will use Visual Studio 2022 to create the web API project. Finally, we will publish the APIs to Azure API Management service.

What is Asp.Net Minimal API?

ASP.NET Core’s minimal APIs are a simplified way to build lightweight APIs with minimal code. You can define your API endpoints in a single file as all necessary configurations and endpoints can be defined within the single file. ASP.Net Minimal API supports DI (Dependency Injection) out of the box allowing you to inject services directly into your endpoints without the need for a separate controller class.

Why use Minimal APIs?

The idea behind Minimal APIs was to reduce the complexity and the files required to create Web APIs. Following are the advantages of using minimal APIs.

  1. Reduces complexities within code by removing unnecessary code and configurations to quickly build HTTP APIs.
  2. Reduces the learning curve for a developer new to ASP.Net Core.
  3. Provides a greater control to a developer building HTTP APIs.
  4. Faster startup time due to reduced dependencies and light weight structure.
  5. Simplified routing allows you to define routes directly in the code, and route parameters can be extracted directly from the route template.

Where to use Minimal APIs?

Use minimal APIs if you want to build microservices or APIs with minimal files or ASP.Net Core dependencies. As minimal APIs are lightweight, they can be used to build APIs or apps which needs that extra performance benefits.

What will we accomplish?

In this article we will accomplish the following tasks

  1. Create minimal APIs to add a product, list all products, get product by id and delete a product.
  2. Publish minimal API project to Azure App service.
  3. Deploy minimal API using Azure API Management.

How to create Minimal API project using ASP.Net Core 7.0?

Let us start by firing our Visual Studio. I will be using Visual Studio 2022 for creating the minimal APIs using ASP.Net Core 7.0.
  1. Create a new project and select ASP.Net Core Empty Project and click next button. Name the project as per your choice and click next.
    Create a new ASP.Net Core Minimal API Project
    Create a new ASP.Net Core Minimal API Project
  2. Select .Net 7.0 and click on create button. Remember to click on “Do not use top-level statements”. This enables you to write code directly at the top level of a file without needing to wrap it in a class or method. More on this in future blog posts.
    Select .Net 7.0 framework
    Select .Net 7.0 framework.
  3. Here you go! Your first Minimal API project is ready. Let us look at the code that is generated.
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();
    app.MapGet("/", () => "Hello World!");
    app.Run();
    1. Notice there is no class declaration or static void Main method for the program’s entry point. This is due to “Do not use top-level statements” checkbox we unselected in earlier step.
    2. WebApplication.CreateBuilder(args) – WebApplication is a class provided by ASP.NET Core for building web applications. It represents the web application itself and is used to configure various aspects of the application, such as routing, middleware, and services. CreateBuilder: CreateBuilder is a static method of the WebApplication class. It is used to create a builder object that allows you to configure the web application before building and running it.
    3. var app = builder.Build() – Calling builder.Build() essentially “seals” the configuration, making it ready to accept and process HTTP requests. It is an essential step in setting up an ASP.NET Core web application, as it prepares the application for execution.
    4. app.MapGet(“/”, () => “Hello World!”) – This statement defines a route and associated handler for handling HTTP GET requests to the root path (“/”) of your web application. When an HTTP GET request to the root path of your application is made, then lambda expression code () => “Hello World!” will be executed, and “Hello World!” will be sent as the response.
  4. Now our minimal API project code setup, let us delve deeper into creating a full CRUD (Create, Read, Update, Delete) APIs for products in ASP.NET Core 7.0 Minimal API. This will involve defining routes and handlers for each API.
    1. We will define a Product class to represent the product entity.
    2. We will define routes and handlers for CRUD operations:
      1. GET /products: Retrieves a list of all products.
      2. GET /products/{id}: Retrieves a specific product by its ID.
      3. POST /products: Creates a new product.
      4. PUT /products/{id}: Updates an existing product by its ID.
      5. DELETE /products/{id}: Deletes a product by its ID.
      6. We will use the Results class to return appropriate HTTP responses for each CRUD operation.
    3. Here is the code
      using Products;

      var products = new List();
      var builder = WebApplication.CreateBuilder(args);
      var app = builder.Build();

      app.MapGet("/products", () =>
      {
        return products.ToList();
      });

      app.MapGet("/products/{id}", (int id) =>
      {
        return products.FirstOrDefault(p => p.Id == id) != null ?   Results.Ok(products.FirstOrDefault(p => p.Id == id)) :   Results.NotFound();
      });
      app.MapPost("/products", (Product product) =>
      {
        product.Id = products.Count + 1;
      products.Add(product);
      return Results.Created($"/products/{product.Id}", product);
      });

      app.MapPut("/products/{id}", (int id, Product updatedProduct) =>
      {
        var existingProduct = products.FirstOrDefault(p => p.Id == id);
        if (existingProduct is not null)
        {
          updatedProduct.Id = id;
          products[products.IndexOf(existingProduct)] = updatedProduct;
          return Results.NoContent();
        }
        else
        {
          return Results.NotFound($"Product with ID {id} not found.");
        }
      });

      app.MapDelete("/products/{id}", (int id) =>
      {
        var productToRemove = products.FirstOrDefault(p => p.Id == id);
        if (productToRemove is not null)
        {
          products.Remove(productToRemove);
          return Results.NoContent();
        }
        else
        {
          return Results.NotFound($"Product with ID {id} not found.");
        }
      });
      app.Run();

      Please note that this is a sample code. In a real-world app, you would want to implement more robust error handling, validation and secure your APIs.

Now, we have our ASP.Net minimal APIs ready, let us go and deploy them to Azure API Management. Before we proceed to publish the APIs to Azure App Services and later Azure API Management, make sure you have an active Azure account. If you do not have one, you can sign up here for a free trial.

Publish Minimal API project to Azure App Service

Let us create an Azure App Service to host our Minimal APIs

  1. Login to your Azure subscription at Azure Portal .
  2. Click on the “+ Create a resource” button.
    Azure Services - How to create Minimal APIs using ASP.Net Core 7.0 and deploy using Azure API Management
    In the search box enter web app. Select web app from the results
    Marketplace - In the search box enter web app. Select web app from the results
  3. Alternatively, on the home page you can hover over App Services icon and click on Web App from Create options (click on down caret icon).
    App Services - How to create Minimal APIs using ASP.Net Core 7.0 and Deploy using Azure API Management
  4. In the “Basics” tab of “Create Web App” screen,
    1. Select your subscription.
    2. Create a new resource group. It is better you create a new resource group as it will be easier to organize, manage and secure Azure resources created for this sample web app.
      Create Web App - How to create Minimal API using ASP.Net Core 7.0 and deploy using Azure API Management
    3. Enter name of for the web app, I have entered “firminimalapiproject”.
    4. Select “Code” as option for Publish.
    5. Runtime stack as .Net 7 STS.
    6. Operating System as windows. With .Net core you are free to choose Linux as well.
    7. For the sample project I have chosen region as East US. In real world setting you should choose the region closest to your user base.
      Instance Details - How to create Minimal APIs using ASP.Net Core 7.0 and deploy using Azure API Management
    8. App Service plan is automatically selected based on the OS and region selection.
    9. You can choose pricing plan as per your needs. I have selected “Free F1” for this sample project.
      Pricing Plans - How to create Minimal APIs using ASP.Net Core 7.0 and deploy using Azure API Management
    10. I have disabled App Insights under Monitoring tab.
    11. For the sake of this blog post, I will not be exploring other tabs, you can choose to review them.
    12. Click on “Review + Create” tab. Review your choices and click on Create button. Azure will start the provisioning your Web App.
    13. Once your deployment is successful, you can navigate to the Web App resource

Let us publish our minimal api project to the newly created Azure Web App

  1. Right-click on your project in Solution Explorer and select “Publish”. Select “Azure“ as an option as target in the Publish popup. Click on Next button.
    Publish - ASP.Net Core 7.0 Minimal APIs to Azure API Management using Visual Studio 2022
  2. Choose Azure App Service (Windows) as “Specific Target” and click on Next button. Please select option according to the choice you made while creating Azure Web App in earlier step.
    Specific Target - Deploy ASP.Net Core 7.0 Minimal API to Azure API App Service using Visual Studio 2.22
  3. In the next screen to select “App Service”, you may have to enter your Azure credentials. This should bring up the subscription and Azure Web App we created in earlier screen. Select the web app we created in earlier step. Also, select “Deploy as Zip package” check box in the bottom and then click on Finish button. Visual studio will now build the project, package the necessary files into a zip archive, and deploy this zip package to the Azure App Service.
    Select Existing Azure App Service - Deploy ASP.Net Core 7.0 Minimal APIs to Azure API Management using Visual Studio 2022
  4. If everything goes fine, you should see profile creation success message. Click on Close button.
    Profile Publish - Deploy ASP.Net Core 7.0 Minimal APIs to Azure App Service using Visual Studio 2022
  5. Click on Publish button in the publish tab.
    Publish Button - How to deploy ASP.Net Core Minimal API to Azure API Management using Visual Studio 2022
  6. On successful publish, Visual Studio 2022 will open the website on your default browser. Congratulations!!! Your first minimal API project is successfully deployed on Azure. Test your APIs using Postman

Deploy Minimal APIs using Azure API Management

Azure API Management is a fully managed API gateway service. It acts as a front door for your APIs, enabling you to create, publish, secure, analyze, manage, and monitor APIs at scale. API Management simplifies the process of exposing APIs to external and internal developers, partners, and third-party applications, while providing essential features to manage and secure the API ecosystem. It is generally a best practice to expose your APIs using Azure API Management.

Follow the steps below to publish your APIs using Azure API Management

  1. From home screen, navigate to “API Management Services” screen. Click on Create button.
  2. In the “Create API Management service” screen, enter or select relevant details.
    Create API Management Screen - Deploy ASP.Net Core 7.0 Minimal APIs and deploy to Azure API Management using Visual Studio 2022
  3. For this sample project, I have chosen pricing tier as Developer.
    API Management Pricing Tier - Deploy ASP.Net Core 7.0 Minimal APIs to Azure API Management
  4. Keeping the scope of this blog post in mind, I have chosen default options in all other tabs.
  5. Click on “Review + Install” tab, review your details. Once you are ready, click on Create button.
  6. On successful deployment of Azure API Management, navigate to the newly created resource.
  7. On the lefthand sidebar menu, click on API. On the right-hand side screen, click on “App Service” for under “Create from Azure resource”. In the “Create from App Service” popup, click on “Browse” button.
    Create from App Service - Deploy ASP.Net Core 7.0 Minimal APIs to Azure API Management
  8. Select “firminimalapiproject” API project hosted on Azure App Service in earlier step.
  9. Required values will be automatically populated in the “Create from App Service” popup. Click on “Create” button. This should successfully import the APIs from Azure App Service to API Management.
  10. For testing the APIs using Postman, you will have to create a new subscription key. From the lefthand sidebar menu, select “Subscriptions” and click on “+ Add subscription”.
  11. Enter details as below and click on “Create” button. This will create a new API key to be used for testing API from Postman.
    New Subscription - Deploy ASP.Net Core 7.0 Minimal APIs to Azure API Management
  12. For getting value of the subscription key, scroll to the right of the table and click on ellipsis button “…” and select Show/hide keys. Key should be displayed in the text box. Use the key value with header “ocp-apim-subscription-key” while making any API request from Postman.
    Remember, the ocp-apim-subscription-key is just one way to authenticate requests in API Management. You can also use other methods such as OAuth tokens, client certificates, or IP whitelisting based on your security requirements.

Conclusion

With this blog post we learned what are minimal APIs and Azure API Management, when to use them, how to create minimal APIs, deploy them to Azure App Service and then deploy minimal APIs to Azure API Management.

Minimal APIs are a great choice for projects like quick prototypes or microservices where simplicity, minimal ceremony, and lack of ASP.Net Web API/MVC overheads are valued. But for complex projects it might not be a good choice due to lack of method documentation, inline code and functional approach makes unit testing harder, ASP.Net Web API is more feature rich and flexible e.g., filters at global, controller or action level gives you fine-grained control, etc. You should make a choice after through consideration.

Hope this blog post helps you to get started in your ASP.Net minimal API and Azure API Management journey.

Happy Coding!!!

Author: Rohit Kukreti