Web API Using EF Core

What is Web API 

  • As the name suggests, is an API over the web which can be accessed using HTTP protocol.
  • We can build Web API using different technologies such as Java, .NET etc. 
  • Web API breaks the limitation of language. For example a web API written in .Net can be utilized by Java and vice verssa, because the request/response format of Web API is JSON which is understood by all language.
  • For example, Twitter's REST APIs provide programmatic access to read and write data using which we can integrate twitter's capabilities into our own application.
  • We can use tools like Fiddler, PostMan and Swagger for testing Web API

.Net Core Web API - 

  • Is an Ideal platform for building RESTful services.
  • Is built on top of ASP.NET and supports ASP.NET request/response pipeline
  • Maps HTTP verbs to method names.
  • Supports different formats of response data. Built-in support for JSON, XML, BSON format.
  • Can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
  • Includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.

 

C:\Users\deepak.kumar\Desktop\webapi-overview.png



HTTP Verb

Usage

HTTPGET

Used to Read Data

HTTPPOST

Create a new resource

HTTPPUT

Update an existing resource

HTTPPATCH

Update an existing resource partially

HTTPDELETE

Deletes an existing resource




How to setup Swagger
  • Install nuget package Swashbuckle.AspNetCore
  • Open Program.cs and write builder.Services.AddSwaggerGen(); just after builder.Services.AddControllers();
  • Write below lines of code before app.run()
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

  • Once done then swagger can be accessed from https://localhost:<portnumber?/swagger/index.html 

 Create web APIs with ASP.NET Core


Important Points:

  • All the controller name should be suffixed with Controller Keyword - Ex. EmployeeController, WeatherforecastController etc. and it must be inherited from ControllerBase class of Namespace Microsoft.AspNetCore.Mvc
  • The route should be defined as [Route("[controller]/[action]")] - It enforces that all endpoints must be accessed with controller and action method

Model Binding

  • There are 4 ways of Model Bindings for the Web API
  • FromQuery - Reads all parameter from query string and this is default binding method for standard data types. This attribute is optional for standard data types, but if we want to bind custom data type using this approach, then it must be explicitly written.
  • FromBody - Reads all parameter from Request body and this is default binding method for custom data types. This attribute is optional for custom  data types, but if we want to bind standard  data type using this approach, then it must be explicitly written.
  • FromHeader - Reads all parameter from Request header
  • FromRoute - Reads all parameter from Request rout itself

How to Create Minimal API

Minimal API is a way of writting the API without use of controllers with minimal dependencies. They are ideal for microservices and apps that want to include only the minimum files, features, and dependencies in ASP.NET Core.


More details are available at the below link.

https://docs.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0&tabs=visual-studio

Why Minimal API

  • Minimal APIs are an alternative way of building HTTP services. They do not replace the MVC framework that we know.
  • However, as someone who is new to ASP.NET, this single file application is easy to understand. We just need to write 4 lines of code to work.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

  • Minimal simply means that it contains the minimum set of components needed to build HTTP APIs, such as routing, model/parameter binding and serialization
  • It is faster compared to MVC

Read Values from appsettings.json

  • appsettings.json is a good way to store application configuration value per environment. We can maintain separate json file per environment (current environment name is managed from ASPNETCORE_ENVIRONMENT attribute of launchSettings.json) and maintain environment specific value. The environment specific file should be named as appsettings.<environment>.json
  • If there is no environment specific file added then the values are read from the appsettings.json else from the environment specific file
  • If the requested information is not available in environment specific file, then the app will read it from default file. If it is not available in default file also then it will return null value.

If the appsettings.json file is structured like the below image, we can write following code to read different values



[HttpGet]

        public ActionResult ReadFromConfig()

        {

            var result = _configuration.GetSection("ConnectionStrings").GetValue<string>("MyFirstAPIContext");

            var result1 = _configuration.GetSection("Logging").GetSection("LogLevel").GetValue<string>("Default");

            var result2 = _configuration["ResourceName123"];

            return Ok($"Value of result is: {result} and Value of result1 is: {result1} and Value of result2 is: {result2}");

        }

Connect Web API to Database using EF code first approach (Using Class Library)

"ConnectionStrings": {
    "WebAPIDBConnection": "Server=(localdb)\\mssqllocaldb;Database=WebAPIWithEF;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
      • Open program.cs and Inject DBContext dependencies just after the line var builder = WebApplication.CreateBuilder(args);
      builder.Services.AddDbContext<WebAPIDBContext>(options =>
          options.UseSqlServer(builder.Configuration.GetConnectionString("WebAPIDBConnection") ??
          throw new InvalidOperationException("Connection string 'WebAPIDBConnection' not found.")));

      • WebAPIDBContext is the name of DBContext class from the library project and WebAPIDBConnection is the key name from appsettings.json file which can be different in your case
      • Add an overloaded constructor in WebAPIDBContext class
      public WebAPIDBContext(DbContextOptions options)
              : base(options)
              {
        }

      • Once the above 3 steps are done, the web API project is ready to connect with database
      • To create a controller, you can also use scaffolding option
      • Right click controller folder and add New Scaffolded Item
      • From next popup, select API Cotroller with actions, using Entity framework
      • It will again open a popup - Select the model for which you want to generate controller, select DB context and give Controller Name and Click Add

      • This step will create a controller with all HttpVerbs and the code will be ready for Select and Crud Operation

              How to add AutoMapper

              • Add the package AutoMapper.Extensions.Microsoft.DependencyInjection from Nuget package manager
              • In Program.cs - just before builder.Services.AddControllers(); write builder.Services.AddAutoMapper(typeof(Program));
              • Create a folder in web API project and give a meaningful name like MappingConfigurations
              • Add a class called AutoMapperProfile (this can be any name) and inherit it from Profile class (this class is available under namespace AutoMapper)
              • Now in any controller if you have to use this utility, declare a variable
               private readonly IMapper _mapper;

              • Add this as a dependency in the constructor

               public EmployeesController(WebAPIDBContext context, IMapper mapper)

                      {

                          _context = context;

                          _mapper = mapper;

                      } 

              •  Use the mapper method in any action method to convert object of 1 type to another type

                          var obj = _mapper.Map<Employee>(employeeAndOrganizationApiModel.Employee);


              Comments

              Popular posts from this blog

              Publish .Net Core Web API to Linux Host

              Entity Relationship Using EF Core Code First Approach