Monday, 20 May 2024

How to deploy asp.net core web api to azure app service

 

How to deploy asp.net core web api to azure app service


In this video we will discuss how to deploy ASP.NET Core Web API along with SQL Server Database to Azure App Service right from with in Visual Studio. The following are the steps.

Create App Service Instance in Azure

In Visual Studio, in the Solution Explorer, right click on the Web API project and click on Publish

Select Azure and click Next

deploy asp.net core web api to azure app service

Select Azure App Service and click Next

deploy asp.net core web api to azure

Click on the + sign. This opens a new window, which allows us to create a new instance of App Service in Azure.

deploy asp.net core api to azure

Provide a name for the App Service Instance. Select your azure Subscription and Resource Group from the respective dropdown list. Click on the New link next to the Hosting Plan dropdownlist. This allows to create a new Hosting Plan.

publish asp.net core api to azure

Provide a name for the hosting plan. Select a Location and the size. Click OK.

visual studio publish api to azure

You should be back on the App Service window, click Create

deploy rest api to azure app service

After a few seconds, App Service instance is created in Azure. By default it is already selected. Click Next.

c# rest api deployment in azure

Azure API Management provides several benefits. We will discuss, what is API Management and the benefits it provide in our upcoming videos. For now, select the checkbox Skip this step and click Finish

azure deploy rest api

Create SQL Database in Azure

Visual Studio is smart enough to detect that our Employee Management API has a dependency on SQL Server database. It is shown under Service Dependencies. Click on the Configure link to create SQL Server Database in Azure.

azure publish rest api

Select Azure SQL Database and click Next

azure deploy web api

Click on the + sign

deploy asp.net web api in azure

Click on the New link next to Database server dropdownlist. Before we can create a SQL Database, we need to create SQL Server Instance.

.net core web api deploy to azure

Provide a Database server name, location, Administrator username, password and click OK.

publish asp.net web api to azure

You are now back on Azure SQL Database. Click Create. This creates SQL Server Instance and the database in azure.

deploy .net core web api to azure app service

Click Next on Configure Azure SQL Database window.

deploying web api with database in azure

Provide a database connection username, password and click Next, then Finish and finally Close.

deploy asp.net web api with database in azure

At this point, you should be back on the Publish page in Visual Studio. We have to tell Visual Studio to execute database migrations when we publish to azure. Click on the Edit link.

web api with sql database deployment in azure

Click on the Settings tab. Expand Entity Framework Migrations. Select Apply this migration on publish checkbox and then Save.

publish web api and sql database to azure

Finally on the Publish page, click the Publish button.

web api deployment in azure

After the deployment is complete. Navigate to the following URLs

  • /api/employees - You will see the list of all employees
  • /swagger/v1/swagger.json - You will see the Emloyee Management OpenAPI specification document.
  • /swagger - You will see the Emloyee Management API documentation.

How to use swagger in asp.net core web api

 

How to use swagger in asp.net core web api


In this video we will discuss how to use swagger in asp.net core web api and automatically generate api documentation. In our upcoming videos we will discuss how to deploy this web api in azure.

asp.net core swagger example

We discussed OpenAPI Specification, Swagger, Swashbuckle and the relationship between them in detail in our previous artcle.

  • OpenAPI is a specification i.e it is a set of rules that specifies how to describe an API. 
  • Swagger is a set of open-source tools built around the OpenAPI Specification.
  • Swashbuckle is a nuget package and it contains Swagger tools for documenting APIs built on Microsoft.NET platform.

Install Swashbuckle.Aspnetcore

To generate documentation for your API, install Swashbuckle.Aspnetcore nuget package. The following are the steps.Right-click the API project in Solution Explorer and select Manage NuGet Packages

  1. Type Swashbuckle.AspNetCore in the search box
  2. Select Swashbuckle.AspNetCore and click Install

"Swashbuckle.AspNetCore" has a dependency on the following packages which are also automatically installed.

asp.net core swagger documentation

Swashbuckle.AspNetCore.SwaggerGen: This package inspects our API routes, controllers, and models and builds the SwaggerDocument objects. 

Swashbuckle.AspNetCore.Swagger: This package exposes SwaggerDocument objects as JSON endpoints.

Swashbuckle.AspNetCore.SwaggerUI: This package interprets SwaggerDocument objects and generates interactive documentation for your API and also lets your users test the API calls directly in the browser.

Configure Swagger Middleware

After the nuget packages are installed, we need to add and configure swagger middleware. In ConfigureServices() method of Startup.cs file, call AddSwaggerGen() method. This method adds the Swagger generator to the services collection.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));

    services.AddScoped<IDepartmentRepository, DepartmentRepository>();
    services.AddScoped<IEmployeeRepository, EmployeeRepository>();
    services.AddControllers();

    services.AddSwaggerGen();
}

In the Configure() method, enable the middleware for serving the generated JSON document and the Swagger UI

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // This middleware serves generated Swagger document as a JSON endpoint
    app.UseSwagger();

    // This middleware serves the Swagger documentation UI
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee API V1");
    });

    // Rest of the code
}

Access Swagger document and API documentation

To see the generated Swagger document i.e the OpenAPI specification document, navigate to http://localhost:<port>/swagger/v1/swagger.json

To see the swagger documentation UI navigate to http://localhost:<port>/swagger

To serve the Swagger UI at the application root URL (http://localhost:<port>/), set the RoutePrefix property to an empty string:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee API V1");
    c.RoutePrefix = string.Empty;
});

Swagger document customization

The generated Swagger JSON document can be customised. This means even the API documentation can be customised, because the API documentation is driven by the generated swagger JSON document. For example, you can use the SwaggerDoc() method to include version, title, description, terms of service, contact person and license terms in the generated json document.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "Employee API",
        Description = "Employee Management API",
        TermsOfService = new Uri("https://pragimtech.com"),
        Contact = new OpenApiContact
        {
            Name = "Venkat",
            Email = "kudvenkat@gmail.com",
            Url = new Uri("https://twitter.com/kudvenkat"),
        },
        License = new OpenApiLicense
        {
            Name = "PragimTech Open License",
            Url = new Uri("https://pragimtech.com"),
        }
    });
});

This is then displayed on the Swagger documentation UI page as shown below.

how to use swagger in asp.net core web api

You can also use XML comments and data annotations to control the generated swagger JSON document and the API documentation.

What is Swagger?

What is Swagger


In this video we will discuss what is swagger and why we use it. Along the way, we will also understand what is OpenAPI specification and Swashbuckle.

difference between swagger and openapi

You may be wondering, why are we talking about Swagger in Azure tutorial? Well, Swagger is the standard for documenting APIs and in our upcoming videos, we will discuss how to deploy APIs in azure. Understanding swagger is helpful when deploying APIs in azure, hence the slight detour. If you already know, what is Swagger, you may skip this video.

Why document APIs

Swagger is primarily used for documenting APIs, but why document APIs? Well, whether you are building APIs that are internal for your enterprise or for public consumption, the theme is the same, they are usually used by developers in the apps that they are building. For the other developers to be able to use your API, it must be properly documented, otherwise how would they know

  • What endpoints are exposed by your API and more importantly 
  • What operations are supported at each available enpoint
  • What parameters to pass and 
  • What will they get back (return value)
  • What authentication methods to use

You don't want to be answering these kind questions over and over again. So, properly documenting APIs is essential, if you want them to be consumed and properly used. 

We will discuss, what is Swagger in just a bit, but before that, let's understand OpenAPI specification.

OpenAPI Specification v/s Swagger Specification

openapi specification vs swaggerLot of people use these 2 terms - OpenAPI specification and Swagger specification interchangeably. Both of them refer to the samething. Initially it was called swagger specification but later renamed to OpenAPI specification. 

What is OpenAPI specification

Well, as the name implies it's a specification. What is a specification in general? Well, it's a set of rules that specifies how to do something. So OpenAPI specification is a set of rules that specifies how to describe our RESTful APIs in a language agnostic way.

Irrespective of which technology we use (Java, PHP, dot net or something else), we want our APIs to be easily consumed by other developers in the apps that they are building. Obvisously for them to be able to do that, they should know all the following.

  • What are the available endpoints, for example /customers, /employees, /orders etc
  • Available operations at each endpoint, for example GET, PUT, POST, DELETE etc
  • What parameters to pass and their data types
  • What will the API return and the data type
  • Authentication methods to use etc.

We want the external world or even our internal clients to know all this information about our API, without necessarily sharing our API source code. So there should be rules and standards around how we describe our API, so everyone will follow the same rules and describe their APIs the same way. So, OpenAPI specification is simply a set of rules that specifies how to describe your RESTful APIs. They have rules for describing every aspect of your RESTful service. For example, you have to follow certain rules to specify 

  • The available endpoints at your API
  • Similarly, there are rules to specify available operations at each endpoint
  • Basically rules for everything - specifying parameters, their data types, return values, authentication methods etc.

So, OpenAPI specification is a standard and language-agnostic way to describe a RESTful API. The idea is to create a document following these rules, either in JSON or YAML format that describes your entire API.

  • Available endpoints, for example /customers, /employees, /orders etc
  • Available operations at each endpoint, for example GET, PUT, POST, DELETE etc
  • What parameters to pass and their data types
  • What will the API return and the data type
  • Authentication methods to use etc.

You can find the full OpenAPI specification at the following link
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md

Benefit of a standardised specification

Well, it allows us to build tools that automate various tasks.

why use openapi

  • For example, let's say you have a CustomerAPI. You can point a tool at this API and ask the tool to generate the OpenAPI specification document for your CustomerAPI.
  • After the OpenAPI specification document is generated, you can then point another tool at this specification document to generate the documentation for your API.
  • Based on this specification, you can also create tools to genereate server stubs and client libraries.

Swagger vs OpenAPI vs Swashbuckle

swagger vs openapi

What is OpenAPI

  • OpenAPI is a specification i.e it is a set of rules that specifies how you should describe your API.

What is Swagger

  • Swagger is a set of open-source tools built around the OpenAPI Specification.
  • Swagger Codegen is one such tool that generates server stubs and client libraries for your API in over 40 languages.
  • Swagger UI is another such tool that generates interactive documentation for your API and also lets your users test the API calls directly in the browser.
  • Though Swagger is primarily used for documenting APIs, it does more than that.

What is Swashbuckle

  • Swashbuckle is a nuget package and it contains Swagger tools for documenting APIs built on Microsoft.NET.