ASP.NET Core 7 Project Setup: REST, API, Routing, Web API, and Swagger

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign in this lesson we will begin our project preparation I will remind you about main Concepts in web programming such as rest API routing HTTP responses and Status codes and then we will create a web template and view it in Swagger now let's open Visual Studio and choose to create a new project in our previous lessons we have been using the ASP net core empty templates however since we are starting a complete API project you will need to select asp.net core web API this choice is necessary because it includes all the essential items we need for this project such as restful HTTP services and controllers it's an extended template commonly used for creating MVC applications just as a reminder you can narrow down the available templates by using the selectors at the top of the screen on the next screen you will need to provide a project name and I'll name it Hi-Fi talk API for the location you can choose any location on your computer but it's better to avoid using spaces in the names and limit the number of subfolders I'll use the same lessons folder and the subfolder will be named after the solution just to recap the solution name is the top level name that can Encompass various projects since our project already contains the work API we should exclude API from the solution name this practice is essential if we plan to extend our solution in the future for example by adding a front-end project a database project or a devops project and so on moving forward I'll let select the framework which is network 7. if this option is not available you'll need to install it either directly from the visual studio installer or by going to the tools menu selecting get tools and features and choosing to install it as we've done in previous lessons unlike our previous projects at this time we need to enable https so make sure to check the https box as it will be used in this project for the other checkboxes we will need to select controllers since we will be working with controllers in this project additionally enable open API support this is essential as it allows asp.net core to automatically document all HTTP endpoints you'll be then able to view this documentation through the Swagger UI now that the project has been created in Visual Studio let's quickly go over the folders and files in the solution Explorer in case the solution Explorer is hidden and you can access it from The View menu or by pressing Ctrl alt L at the top we have our solution which includes the project name since the project is about an API we have added the API work to the project name the solution can hold multiple projects that we may need if you navigate to the folder on your computer where you store your files you will find that the solution file has a sln extension using this structure with the solution containing projects we can effectively organize the project structure each project will have a specific set of folders and files inside clicking on the project name will open a file with a CS approach extension now this file is utilized by the visual studio development environment in network projects it contains metadata and configuration settings for the c-sharp project essentially defining its structure additionally packages we installed will be reflected here and we can disable these packages if needed the presence of savage Buckle indicates that Swagger is installed in this project inside the properties folder there is a file named launch settings and while we have discussed this file in detail in previous lessons I'll provide a quick reminder this file controls which server we will use whether it's Kestrel is Express or others that might require additional installations unlike Apache or nginx both Castrol and IIs Express are available out of the box with a netcore 7 installation if you need to remember the port number where the server will respond and you can find it in this file when you run the project the server will respond on the port specified in the string and the project work with the command name option says that Kestrel will be used Additionally you can rename the HTTP or https and names for better understanding and the updated name will be reflected in the main bar in the same menu you can choose your favorite browser which will be launched when you build and run your project or whether the browser should start automatically or not can be configured using the launch browser parameter in the build settings file in my case I will set it to false since we were previously using only HTTP you will need to choose the https profile on the main bar for this project the configuration for https execution is handled in this section of the configuration file the https profile includes both port numbers for https and HTTP the port numbers are random and if you recreate Your solution or project this ports will be changed by the new project automatically therefore please ensure that you follow your own settings as my port and your ports will be different the controllers folder was not provided in our previous use of netcore empty templates but it's included in the template we chose this time as we discussed in previous lessons the up settings file contains various levels of login settings with the default level being information it also may include database connection strings environment settings such as production or development API Keys runtime variables and many other configuration options the program file serves at the entry point of the application executing the application and providing dependency injection as we discussed in previous lessons in general you can split this file as follows this string is used to create an instance of a web application builder in asp.net core application this section is responsible for configuring and adding services to the dependency injection container this line builds the application using the configuration and services setup earlier at this part configures the middleware components that handle incoming HTTP requests and responses it includes enabling Swagger documentation generation in a development environment setting up https redirection and adding authorization middleware of this line Maps controllers and their Associated actions to specific routes in the application it ensures that HTTP requests are routed to the appropriate controller method for processing and this line starts the application and begins a lesson for incoming HTTP requests it essentially kicks off the web server and keeps the application running to handle requests then after the app run method is executed at the Middle where pipeline is being processed and if no earlier middleware components have generated the response or terminated the request the application will continue to process the request by looking for an action method within the controllers to execute in response to an incoming request so that's a part of MVC pattern and again quickly just to refresh what was explained in the previous lessons rest or representation of State transfer and architectural style for Designing Network application that uses standard principles including resources statelessness and standard HTTP methods restful describes an application or service that follows the principles of rest using URLs HTTP methods and a uniform interface the stateless API means that the system or component such as a web API does not retain any information or session data about previous interactions with a client and stateful API refers to a system or component that retains information or assertion data about previous interactions with a client access to the API is achieved using request types with four primary request types being get post put and delete other request types are used as needed but these are the most commonly used it's worth nothing that all these request types can be applied to the same endpoint routing is a process of mapping incoming HTTP requests to a controller and then to a specific action method within that controller let's see a routing example this code is defining routing and controllers in asp.net core application the route API tasks attribute is applied to the task controller class this attribute specifies a base route for all the actions methods within the controller in this case all actions within task controller will be reachable under the base route API tasks each action method within the task control is decorated with an HTTP verb attribute such as HTTP get post put and so on this attributes Define the HTTP verb like get postput and the route button for each option for example HTTP get ID and Maps the gear task method to the HTTP get verb with the route button that includes an ID parameter in the URL this allows you to retrieve a specific task by its ID the action methods themselves Define the logic to be executed when a request with a matching HTTP verb and Route button is received for instance the gear task method retrieves a task by ID the create task method creates a new task and so on so this combination of Route attributes HTTP verb attributes and action methods is how routing is defined and implemented in ASP net core controllers it determines how incoming HTTP requests are mapped to specific control actions and how responses are generated no worries if we will cover these Topics in future lessons as a reminder are the most commonly used HTTP status codes are on your screen we will be working with status codes frequently and for a more extensive explanation about HTTP status codes please refer to previous lessons where everything was explained in detail the template provided by Visual Studio after creating the project includes predefined controller logic this logic will be executed as soon as we access it to build and executed you can use Ctrl shift b or press F5 with debugging or Ctrl F5 without debugging alternatively you can use the respectively buttons in my case I will press Ctrl F5 to build and execute it after pressing controller 5 Swagger should start automatically if it hasn't happened you need to verify that Swagger was installed as a part of the visual studio installation on your PC and ensure it's included and enabled in your projects packages you can check this by opening your projects configuration file away it should be visible under the swashbuckle name you can also verify that your build is running correctly by going to the localhost address with the port assigned respectively and then entering weather forecast you should receive a response as you can see on my screen a few words about Swagger Swagger simplifies the process of Designing documenting and interacting with restful apis it promotes better API understanding collaboration among developers teams and the generation of client and server code ultimately improving the efficiency of API development we will be using swagger and all these details will be explained throughout this course it's opened on my computer in accordance with the port configuration in the launch settings Json file we discussed earlier and the string contains localhost which refers to your computer and the port number assigned by the template a port number is a numerical identifier used to distinguish Network Services running on the same host or simply computer after starting the project we can see that Swagger has added an index HTML for this index file serves to provide the current user interface allowing you to conveniently interact with and explore your API endpoints so let's take a look at the code the current API contains a single endpoint called weather forecast a decent Point contains only one declared method which is a get when we access this endpoint we get the logic displayed using the get method the weather forecast endpoint when accessed directly or will be displayed in the following format with no additional technical data displayed however when we access this endpoint in Swagger or we get extensive information this includes the method type which is a get in this example if we expand it we can see the status quo 200 with its description media type and an example response value moreover we can go even deeper by pressing try it out and then execute now we get a Serial command aware C URL stands for client URL X denotes to the type of method like get post and so on H represents headers followed by the URL received with the request including the response body and response header as you can see all of this information is in accordance with the code now let's add a controller as you may remember from previous lessons if you right click on the controllers folder the add menu provides a controller option directly alternatively you can access it from the new item menu then from add new scaffolded item select API since we are creating an API and choose API controller empty from there please remember that when adding a controller the name should include the controller suffix otherwise netcore won't detect it as a controller I'll name it planets controller I'll explain this template quote quickly and when we create a controller we usually get the token replacement in asp.net core 7 when you use this record route controller as an attribute on a controller class each part of the feature called token replacement in attribute routing the controller token in the route attribute will be automatically replaced with the name of the controller class without the controller suffix this is a convention that allows you to create routes based on the controllers name without having to hard code it that's why you can access this route using API planets so it will look like this localhost port API planet now in order to guide the server in processing the request we need to register an HTTP method to interact with resources I will add a geared attribute and a method or this attribute HTTP get will decorate the controller action method get planets it specifically indicates that the decorated method should respond to http get requests regarding the I action result interface I have covered it in at least three lessons so it would be better if you familiarize yourself with this interface as it's as substantial and important topic that may rise questions finally we return an instance of the Json result class along with our planet's names these Clauses like Json result explained in previous lessons so I won't comment on them again in Swagger we now have an additional endpoint called planets similarly if we access this endpoint directly using the get method which is the browser's default method we receive a response accordingly so now we have two controllers with different endpoints and these endpoints can be further extended for example with a post request to try out the post request we need either a simple web form or as we have discussed before a tool like Postman just as a brief reminder Postman is a tool and collaboration platform for Designing testing and documenting kpis it provides all the tools necessary for developers testers and teams to streamline the API development and tasting process now let's start with Postman I will run the endpoint and as you can see the endpoint replied also we have all the information in the reply so you can choose any tool you like either Swagger or Postman but since we were using Postman earlier let's mainly Focus now on Swagger for your better practice thanks for watching if you have any questions or need further assistance feel free to comment below don't forget to hit that like button and subscribe to our channel for more great coding content and stay updated with the latest videos by ringing the notification Bell happy coding
Info
Channel: hikitoc
Views: 786
Rating: undefined out of 5
Keywords:
Id: KP2uDBn0HJk
Channel Id: undefined
Length: 17min 24sec (1044 seconds)
Published: Sat Sep 23 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.