Web Services (a.k.a APIs) can allow applications to validate user credentials from Facebook and Google servers without making copies of databases, thereby overcoming all the problems mentioned earlier in the travel company case study. As an advantage of using Web API, the travel company will get the following benefits: 1. No need to maintain replicas of other company's databases. S 2. No need to sync up with main databases when there is a change. 3. Can easily add new providers as and when needed. Web services are standardized medium to propagate communication between the client and server applications on the WWW (World Wide Web Web services: 1.Simple Object Access ProtocolSOAP defines an XML-based protocol for accessing Web Services. It can use different transport protocols like HTTP and SMTP --Works withsoap apirest apiWSDL works with XML based Interface Description Language 2.REpresentational State TransferRESTful services are developed using HTTP methods and are accessed using the HTTP protocol, a stateless protocol --It works with Http attributes such as GET, PUT, POST, DELETE Controller is a class that contains service methods to receive requests and provide responses. . It handles incoming HTTP requests and sends responses back to the caller. The methods in the Controller are called Actions. All the action methods (services) can return one of the following types as a return value: Specific type (void, int, bool, JsonResult etc.) ActionResult IActionResult ActionResult: ActionResult is the result of Action when it is executed. This return type has many other derived types and are listed in the table below WebApplication.CreateBuilder() method Initializes a new instance of the WebApplicationBuilder class with preconfigured defaults and assigns to a variable builder. Using the builder, the other service configurations are done. Services.AddControllers() method takes care of registering the controllers, model binding and API exploration. Services.AddEndpointsApiExplorer() method is used to create Endpoint instances and register them with the routing system. Services.AddSwaggerGen() is a Swagger generator that builds SwaggerDocument objects directly from the routes, controllers, and models. You will learn about routes, controllers and models as you proceed through the course. Swagger is a platform which helps user to build, document, test and consume RESTful web services. UseSwagger( ) and UseSwaggerUI( ) are the methods to direct the output to be displayed on Swagger. In the above code, app.UseHttpsRedirection() will issue HTTP response codes redirecting the http request to https. app.UseAuthorization() will check if authorization is used by the web app. app.MapControllers() will set up the routing for controller actions within the application, allowing the API to map HTTP requests to specific controller methods. app.Run() will enable automatic run once executed. 1. To create HttpGet method To read the details from the database Since we are designing a stateless web service, we would be using AddTransient( ) to perform dependency injection. builder.Services.AddTransient(); builder.Services.AddTransient( c => new QuickKartRepository(c.GetRequiredService())); In order to connect to the database through data access layer you need the connection string. Every controller method of a web API can be associated with an HTTP attribute (HttpGet, HttpPost, HttpPut or HttpDelete). HttpGet attribute makes the controller method discoverable as a service method to respond to browser's http get request. If no method is associated with the Action, HttpGet will be the default attribute. [HttpGet] public JsonResult GetAllProducts() { List products = new List(); try { products = repository.GetAllProducts(); } catch (Exception ex) { products = null; } return Json(products); } BODY->RAW-JASON (AddProductUsingModels) RedirectResult-Redirects to the specified URI RedirectToRouteResult-Redirects to the actions within the application HttpStatusCodeResult -Returns specific HTTP status code to the browser HttpUnauthorizedResult -Represents the return of an unauthorized access to the client HttpNotfoundResult -Informs the browser that the resource was not found What are the resources that are supported by RESTful services? XML,HTML,JSON Which of the following is responsible to launch the application, including all environment variables that should be used in the entire project? launchsettings.json Which REST constraint specifies that there should be no shared context? Stateless Which of the following defines appsettings.json It can be used to store custom application settings, DB Connection strings, logging etc ----------------------------------GET----------------------------------- AddTransient - New instances created for every request Every controller method of a web API can be associated with an HTTP attribute (HttpGet, HttpPost, HttpPut or HttpDelete). HttpGet attribute makes the controller method discoverable as a service method to respond to browser's http get request. If no method is associated with the Action, HttpGet will be the default attribute. If there are navigational properties present in models class of data access layer, there is a chance of exceeding the maximum allowed depth of 32 for Json conversion. Observe the output that two properties namely category and purchaseDetails are returned with default values. This can be ignored so that it saves space and increases readability. To avoid this, you need to mention the annotation [JsonIgnore] on the navigation properties which will ignore the navigational properties while converting to Json. Add the required namespace to support JsonIgnore as shown below in the Products class using System.Text.Json.Serialization; Swagger helps users build,document ,test and consume Restful web services PostMan -it is a http client that tests HTTP requests,utilizing a praphical user interfce through which you can obtain diff types of responses that need to be subsequently valudated STATUS CODES: 200 - OK ->Successful operaion 301 -Moved permanently 302 -object moved 400 -bad request 403 -forbidden 404 -not found 500 -internal server error/Uncaught exception 501 -not implemented server error 502 -bad gateway 503 -Service Unavailable 504 -gatewayTimeout 507 -unecpectes exchange mailbox ------------------POST---------CREATE-----ADD----------------------------- [HttpPost] attribute allows browser/client application to access this service method only by posting data (explicitly mentioning request type as post). This post service will typically perform Create operation in the database. ---------------------------PUT-----UPDATE--------------------------------- [HttpPut] is used to indicate that the action method has the logic to update the data. ---------------------------------------- ASP.NET Web Api Core allows you to define service-specific classes as part of its model classes. This concept of the model is a part of the MVC (Model-View-Controller) application design. Model :The part of the software that handles application logic and data related to business. Controller : The part of the software that handles user input. It responds to user input nd informs the other two parts to make appropriate changes (to display to end user-View part, manage data-Model part) The part of the software that handles user input. It responds to user input and informs the other two parts to make appropriate changes (to display to end user-View part, manage data-Model part) View : The part of the software that handles what is to be displayed to user (output) and takes data from the Model In Service Layer, you will work with M and C of MVC. You will not create any Views. Whenever you define a service specific class (model class), you have to take the responsibility of translating the service specific entity (service model) to source entity (DAL project entity) and vice-versa. You will now create to update product details using service model class and also apply data annotations to it, to validate the input. Data Annotations: Qualification should be between 2 to 10 characters. [StringLength(10, MinimumLength=2)] Age should be between 18 to 64 . [Range(1,64)] Regular Expression, regex or regexp is a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. They are used to match strings and substrings using patterns as delimiters to reformat text in a required format. Regular Expressions are used to solve and manipulate the given string. Here you are going to use System.Text.RegularExpressions namespace in .NET Framework. This includes predefined meta characters. [RegularExpression(@"^[a-zA-Z]{4,100}")] [StringLength(100, MinimumLength=4)] ModelState.IsValid provides a value that indicates whether this instance of the model-state dictionary is valid. ---------------DELETE----------------- HttpDelete ServiceAn HttpDelete service can be used to delete an entity from a data source.HttpDelete is an idempotent operation. In case of idempotent request, making multiple identical requests to the same endpoint will always get the same response. If the deletion is successful, you will return true. In case of failure or exception, you will return false. Note: In practical business scenario, you will prefer not to delete any item but make it inactive by changing the status in database. The ability to invoke a RESTful method multiple times without changing the state of the server on subsequent invocations -Idempotence -------------ROUTING-------------WEB API----------------------- How does the browser understand which controller and action to be invoked based on the request submitted??? When the HTTP request is received, the framework uses a routing table to match the URI against one of the route templates available in the routing table. Once a matching route is found in the route table, the Web API Framework selects the controller and the action. The Web API Framework adds "Controller" to the value of the {controller} in URI and HTTP method of the incoming request (i.e., GET, POST, PUT or DELETE) to look for an action method with the HTTP verb attribute received in the URI. If no route template matches the URI, then Web API Framework returns a 404 error to the client making the request Basically, there are two types of Routing used during application development. 1.Convention-based Routing In convention-based routing, you will configure the route through the MapControllerRoute method inside Program.cs, by using various parameters like name, pattern and defaults.The advantage of using this routing type is that the templates are defined in a single location in application. Hence they are easy to maintain. 2.Attribute-Routing Attribute routing is the process of attaching a route, as an attribute, to a specific controller or action method. Decorating a controller and its method with [Route] attribute to define routes is called Attribute Routing.Inside the controller, we configure the Route template. We mention a prefix 'api' (default and can be changed) followed by the controller's name to compose the URI for action/method invocation. The details of the parameters used in MapControllerRoute are: name: The name of the route. pattern: The URL pattern of the route is the unique identification of the action to be invoked. The pattern is controller/action/id, where the id is an optional value and hence appended with a ‘?’. defaults: An object that contains default values for route parameters. The object’s properties represent the names and values of the defaults, if the user does not provide a value for controller and action. You can see a Route with the name "ProductRoute” and it has a URL pattern “Product/{id:int}” which tells that any URL that starts with /Product, must be handled by ProductController. The URL will be /Product/id where id can be any integer value. ->A controller ‘Library’ has an action books. How would a URL look like to search for a book based on its id? Assumptions: Route is configured as [api/[controller]/[action]] id to be passed is 1 --api/Library/books/1 ->What is the use of MapControllerRoute() --Configures the Route ----------Minimal---API--------------- In .NET 6, a new feature of Minimal APIs has been introduced. This allows us to create an API with minimum code. Minimal API's are microservices and apps that want to include minimum files, features, and dependencies. Minimal APIs are architected to create HTTP APIs with minimal dependencies. Identify the correct statements: Minimal API’s are light weight Minimal API’s features are nascent and growing