Introduction to Web API Technology

Time:2019-9-9

Web API

12
OVERVIEW

CREATING AND USING ODATA SERVICES
USING AZURE FUNCTIONS
SUMMARY

Summary

The goal of Web API is to make a communication technology very flexible and meet all requirements. WCF was originally based on SOAP (Simple Object Access Protocol). Today, we have many scenarios that do not require powerful SOAP enhancements. For simpler scenarios, such as HTTP requests returning to JSON, WCF is too complex.
The Web API provides a simple communication technology based on Representational State Transfer (REST). REST is an architectural style based on certain constraints. Compare service based on REST architecture style with service using SOAP.
Same:

  • Both services using SOAP protocol and REST services use client-server technology.

Different:

  • SOAP services can be stateless or stateless; REST services are always stateless.
  • SOAP defines its own message format, with headings and body to select the method of service.
  • With REST, HTTP predicates such as GET, POST, PUT and DELETE can be used. GET is used to retrieve resources, POST is used to add new resources, PUT is used to update resources, and DELETE is used to delete resources.

This chapter takes you through a journey that covers various important aspects of the Web API using ASP.NET Core MVC—creating a service, using different routing methods, creating a client, using OData, securing the service, and using custom hosts. The chapter shows you how you can take the same services created for hosting with ASP.NET Core and use them from Microsoft Azure Functions, which is another option to create a Web API with C# and .NET.

This chapter will introduce you to the journey of using ASP.NET Core MVC to create services, different routing methods to create clients, OData to protect services and various important aspects of the Web API using custom hosts. This chapter shows you how to use ASP.NET Core to create the same services for hosting and use them from Microsoft Azure Functions, which is another option for creating Web APIs using C # and. NET.

service

Create a WebApi using the default template.
Introduction to Web API Technology

` In larger applications, separate libraries are recommended.
If you create libraries containing services and models, you can easily use the same types from different technologies (for example, Web API projects and Azure Functions).
The implementation of Web Api (controller) can also be separated from the host application. `

Define model

Code: BookChapter.cs

Creating services

Define service interfaces
Code: IBookChaptersService. CS (sync part)

Define services for retrieving, adding and updating book chapters.
Code: BookChapters Service. CS (sync part)

Create SampleChapters to populate the data.
Code: SampleChapters.cs

In the host application, the DI registration service is used.
Code: Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    IMvcBuilder mvcBuilder = services.AddMvc();
    mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    # Region Change Response Format
    mvcBuilder.AddXmlSerializerFormatters();
    #endregion
    # Region Registration Service
    // BookChapters Service is registered as a singleton, so it can be accessed from multiple threads at the same time.
    // That's why Concurrent Dictionary is needed in implementation
    services.AddSingleton<IBookChaptersService, BookChaptersService>();
    services.AddSingleton<SampleChapters>();
    #endregion
}

Call SampleChapters for retrieval.
Code: Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env,SampleChapters sampleChapters)
{
    //..
    sampleChapters.CreateSampleChapters();
}

Create Controller

Code: BookChapters Controller.cs

Operation effect
Introduction to Web API Technology

Change the response format

Return to XML — configured as follows:

// Change the response format
[Produces("application/json","application/xml")]
[Route("api/[controller]")]
// [ApiController]
public class BookChaptersController : Controller
{
}
public void ConfigureServices(IServiceCollection services)
{
    IMvcBuilder mvcBuilder = services.AddMvc();
    mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    # Region Change Response Format
    mvcBuilder.AddXmlSerializerFormatters();
    #endregion
    # Region Registration Service
    // BookChapters Service is registered as a singleton, so it can be accessed from multiple threads at the same time.
    // That's why Concurrent Dictionary is needed in implementation
    services.AddSingleton<IBookChaptersService, BookChaptersService>();
    services.AddSingleton<SampleChapters>();
    #endregion
}

REST results and status codes

The results returned by the HTTP method are:

Http Method Description Request Body Response Body
GET Return resources Empty The resource
POST Increasing resources The resource to add The resource
PUT Renewal of resources The resource to update None
DELETE Delete resources Empty Empty

The following table shows important HTTP status codes. The instantiated object (with state code) returned by the Controller method. If you want to return any HTTP status code, you can return a HttpStatusCodeResult object, which can be initialized using the state code you need:

Http Status Code Controller Method Type
200 OK Ok OkResult
201 Created CreatedAtRoute CreatedAtRouteResult
204 No Content NoContent NoContentResult
400 Bad Request BadRequest BadRequestResult
401 Unauthorized Unauthorized UnauthorizedResult
404 Not Found NotFound NotFoundResult
Any status code StatusCodeResult

Asynchronous services

Because many technologies, such as invoking other services using the HttpClient class, provide only asynchronous methods. So there will be asynchronous services.

Define service interfaces
Code: IBook Chapters Service. CS (async part)

Define services for retrieving, adding and updating book chapters.
Code: BookChapters Service. CS (async part)

The BookChaptersService class implements an asynchronous method. When reading and writing from a dictionary, there is no need for asynchronous functionality, so Task uses the FromResult method to create the return value.

Client Configuration

Send requests and receive data from clients. Including GET, POST, PUT, DELETE.
Returns strings in Json and XML formats.

Creating UrlService – Providing Base Address and URI
Code: UrlService.cs

Create a generic class HttpClientService to use an implementation for different data types.
Code: HttpClientService.cs

Create Model – BookChapter
Code: BookChapter.cs

Create client class to make calls to HttpClientService
Code: SampleRequestClient.cs

Register service, call SampleRequestClient
Code: Program.cs

Connect to the database

Create DbContext
Code: DbContext.cs

Create DBBook Chapters Service instead of BookChapters Service
Code: DBBook Chapters Service.cs

Registration Service – ConfigureServices Configuration
Code: Startup.cs

Configure connection string
Code: appsettings.json

OpenAPI(Swagger)

Add NuGet — Swashbuckle. AspNetCore

public void ConfigureServices(IServiceCollection services)
{
    // ...
    // OpenAPI
    services.AddSwaggerGen(options =>
    {
        //options.DescribeAllEnumsAsStrings();
        options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
        {
            Title = "Azure Adapter Api - Catalog HTTP API",
            Version = "v1",
            Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample",
            TermsOfService = "Terms Of Service"
        });
    });
    //...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,SampleChapters sampleChapters)
{
    // ...
    // OpenAPI
    app.UseSwagger().UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
}

Introduction to Web API Technology

OData

Define Model-Book, BookChapter

Define DBContext – BooksContext

Define Service-CreateBooksService

Recommended Today

Comparison and analysis of Py = > redis and python operation redis syntax

preface R: For redis cli P: Redis for Python get ready pip install redis pool = redis.ConnectionPool(host=’39.107.86.223′, port=6379, db=1) redis = redis.Redis(connection_pool=pool) Redis. All commands I have omitted all the following commands. If there are conflicts with Python built-in functions, I will add redis Global command Dbsize (number of returned keys) R: dbsize P: print(redis.dbsize()) […]