How to Create a Web API with ASP.NET CORE and .NET 6 (c# for beginners)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video i will show you how to create a web api with asp.net core we will talk about what a web api is we will create one using asp.net core and.net 6. finally we will consume the web api from a dot net client application let's get into it what is a web api first let's explain the term api an api is a set of functions that developers use to access different functionalities from third-party software as developers we use apis all the time for tasks such as getting the current time creating files and so on a web api is a type of api that uses the http protocol http is a protocol that is mostly used for serving web content when we try to access a website for instance we make an http request to a server and the server sends back html content with web api you request a resource on the server instead of getting html from the server you will get data in json or xml there are many types of web apis res api is the most popular type of web api it lets you convert any data into a resource that can be read create update or delete it by using http methods like get passed put and delete a resource is something that can be named and identified on the web rpc is another form of web api the client sends a method name and argument to a server which returns json or xml data while res is about resources rpc is about actions graphql is a form of web api where there is a single endpoint the client indicates in the body of the request if he wants to perform a query or a mutation using http methods get or post all the different type of web api comes with strengths and weakness this tutorial is about to rest api let's take a look at the flow of a request the client makes a request the request is made to an endpoint which is a url the request uses one of the http methods get passed put and delete to let the server know which action to take get is used for reading data post is used for creating data put or patch are used for updating data and delete is for deleting data the request can have additional information for the server in the headers some requests can have information in the body the server returns a response with data regarding a resource the response can have information for the client the response has data in its body so the response data can be formatted in json or xml but json is the most popular a web api can provide a service you can use the stripe api for instance to integrate payments in your application you can also use a web api to create a backend for a mobile application or a single page application a web api can also be used to exchange data between two different systems now that we know what a web api is it's time to create one in my last video how to create a web application using asp.net core razer pages i created an issue tracking web application i will use the same id by this time we will create a web api that allows crowd operations on issues we will expose different endpoints one for getting all the issues one for getting a single issues by id one for creating an issue one for modifying an issue and finally one for deleting an issue i will be using visual studio 2022 if you want to follow along make sure the web development workload is installed let's start by creating the project in visual studio select create a new project select the template asp.net core web api then click next in this dialog set the project name i name it tracking api and click on the next button i leave the dot net 6 as the framework i also leave the authentication type to none the configure for https is selected this enables ssl the checkbox right here says use controllers this means that we will create the web api using the mvc pattern you can also create web api using minimal api which is a way of creating web api without controllers if you never heard of minimal api i have a tutorial for that the checkbox right here says enable open api support this will allow us to use a tool called swagger to generate the documentation for the api click on the create button to generate the project the project is created let's take a look at the file generated by visual studio the file name weather forecast is a model which is used to generate a web api that can show the weather forecast so this was created by in the generation process program.cs is the entry point of the application this is where the app is bootstrapped we will use it to register services for dependency injection app settings.json is where you store the application configurations such as connection string for instance the folder controllers contains controllers there is one already created when generating the project a controller is used to process the request in the properties folder there is a file called launch settings.json this file contains settings that describe how the application is launched it is meant to be used only on your local machine let's run the project to make sure everything works correctly the first time you launch the project you will see a warning message the browser is complaining because we are using a development certificate that it can't verify to resolve this issue i go into the advanced options and i click to accept the risk and continue as you can see this is our web api thanks to the swagger the api is documented you can see that we have one endpoint for the weather forecast swagger also allow us to test the api within the browser just by clicking on the endpoint name then try it out if i click on the execute button you can see i get the results so these are the value returns by the weather forecast controller let's get rid of these classes because we are going to create new ones we will use entity framework core in order to interact with the database the goal of entity framework core is to use c-sharp classes instead of sql tables there are two main approaches when working with ef core database first where a model is created from a database or code first where the database is generated based on the model we will use the latter the first step is to create the model at the root of the project add a new folder call it models inside this folder add a new c-sharp class call it issue this class represents a single issue in order to describe an issue first we need an id this will be the primary key next we need a title we also need a description an issue can have a priority let's add a enum named priority a priority can be low medium or i then we can add it to the issue model next let's add a enum name it issue type it will describe the type of an issue the possible values are feature bug and documentation let's add the property issue type next we need to capture the time when the issue was created for that add a date time property name it created finally add the last property which is also a date time but this time we are going to use a nullable date time we name it completed if this property is null it means the issue is not completed yet otherwise the issue is complete let's add some validation attributes on the title and on the description the required attribute specifies that these properties must have a value the model is done now we are going to install some nuget packages needed in order to work with entity framework core let's go to the nuget package manager window because we are going to use sql server as the database we need to install the package provider for entity framework call the next package we are going to need is the entity framework core tools for the nuget package manager this package will allow us to run migrations in order to generate the database and keep the model in sync with the database if we make some changes to communicate to the database we need a special object called the data context this object is used to interact with the database in the project folder add a new folder name it data inside this data folder add a new class name it issue db context the dbcontext is a class that inherits from a class named db context this class comes from the entity framework core package that's why we need to add the using directive next we need to declare a parameter in the constructor the type is dbcontext options this allows setting some options needed by the db context like the connection string for instance so that the db context know how to talk to the database next we need to declare a db set the db set is a representation of the table in the database it will allow us to manipulate data from the table issue the db context is done we are going to register it with the dependency injection container this way we can request an instance in the controller registration for dependency injections take place in the program.cs file use the services property exposed by the builder object invoke the method add db context you need to provide the type parameter which is the issue db context this way we are adding the data context to the service container and a new instance of the db context will be created per request the adddb context method takes an action of db context options builder we can use this to configure the options on the db context that's why we declare the db context options in the constructor we use the method use sql server to set the connection string of the database let's declare the connection string a good location for that is the file app settings.json add a new entry name it connection strings because we can have many connection strings we are going to name it sql server i'm going to copy the value from this file the connection string points out to my local sql server instance now the data context is set and ready to be used but before that we need to generate the database using migrations migrations allow updating the database with the latest changes on the model if you change something in the model you want the changes to be reflected in the database that's where migration comes into play to use migrations i'm going to use the package manager console for that go into the menu select tools then nuget package manager then package manager console use the command add migration a migration name is required and the output parameter allows to choose the location where migration will be created the recursion is going to be data slash migrations if you execute the command you can see that migrations have been created this should be used to create the database if you go back to the package manager console now we can use command called update database if i execute this command it will create the database to make sure the database was created i'm going to use an app called azure data studio this is a tool that allows me to inspect the database if i go to the database you can see here i have a database called issuedb the first table is for storing migrations and the second table is for issues now we have the database it's time to create the points in the folder controllers right click on the folder and select controllers in the menu be careful to select a template from the api controller not from the mvc then click on the head button name the controller issue controller then click on add to create the controller a controller is a class that inherits from controllerbiz and contains action which will process the request the controller base class provides useful properties and methods to help you manage http requests we will see some of them later you can change the behavior of the controllers and action methods by using attributes that come from the namespace microsoft microsoft.asp.net core dot mvc the api controller attribute is used to apply common conventions to your controller like automatic validation of the model binding request data to the model and so on the route attribute allows mapping request actions methods it can be applied at the controller level or at the action level the template provided here specified that we will request the api using the url api slash the name of the controller minus the controller suffix the controller will have to access the database for that declare the dbcontext in the constructor this way we will get an instance of it at runtime let's create our first action method an action method is a public method that is executed in response to an http request we are going to create an action method that will be mapped to the http verb get in order to get a list of issues the method returns an i animal of issue we name it get the name is not that important we decorate the method with the http get attribute to specify that the method will handle http get request in the method itself use the context to retrieve the issues and use the method to list essence to return the issues and that's it this action method will respond to an http request and return a list of issues as the response let's run the application you can see the endpoint with the url template click on it you can see the description of the endpoint the expected parameters of the request and the expected response to try the request click on the try it out button then execute in the response section you can see the result of the request because the database is empty we have no data but let's put a breakpoint in the get method and let's try again you can see that the breakpoint is hit we are able to reach the action method with the http get request let's add a new action method that will handle http get request with a parameter in order to return a single issue the method returns an i action result i name it get by id it has an id parameter that represents the id of an issue we decorate it with the http get attribute to specify that it will handle http get request but this time we add an id placeholder this makes the action to respond to requests that have the id at the end of the url in this case the url will be api slash issues slash sum issue id the id in the url will be bound to the id parameter of the method now i get the issue using the context if the issue is not found i return a not found result using the method not found otherwise i return an ok object result using the ok method the not found will generate a 4 or 4 status code in the response whereas the ik will generate a 200 status code in the response in case you wonder where these methods come from they come from the controller base class because we can return to type of response that's why we return an i action result we can enhance the documentation with the attribute produce response type first to describe that the method returns an issue type with a 200 status code then to describe that the method can return a 404 status card let's run the application you can see the new endpoint in the parameters section you can see that the request expects an id parameter in the response section you can see the possible return status code we are not going to try the request because we still don't have there we'll try out later so now let's add a method for creating a new issue the method returns an i action result i name it create it takes an issue object as a parameter this parameter will be bound to the body of the request i decorate the method with the http passed attribute in the body of the method add the issue submitted by the request to the issues collection exposed by the context invoke save changes async to propagate changes to the database for the response we are going to use another helper method called created at action this helps return the response with the status code and the location in the editor it takes three parameters the action that returns a single issue in this case gate by id the id of the issue as an anonymous object and finally the issue itself we can also decorate the method with the produce response type attribute to specify that it returns a 201 status code let's run the application you can see the new endpoint if you click on the try it out button you can fill in the request body and if i execute the request you can see in the response section the created issue also if you look in the response header you will see the url to retrieve the created issue now let's add a new payload and leave the title empty if i execute the request you can see that i get a bad request response i didn't do anything to validate the issue the framework take cares of it because of the api controller attribute we set on the controller now let's add an action method for updating an issue the method returns an i action result we name it update because an http people to require the id of the issue we want to update and the new issue we declare an id parameter and an issue parameter the id will be bound to the id in the url and the issue will be bound to the body of the request we decorate the method with the http put attribute the id placeholder specified that the id will be in the url first we need to check if there is a mismatch between the id in the url and the id in the body if it is the case we return a bad request otherwise we update the issue and propagate changes to the database we return a no content result this will return a 204 status code in the response finally let's enhance the documentation with the produce response type attribute we specify that the method can return a 204 status card we also specify that the method can also return a 4 o or status code so let's run the application you can see the new endpoint first we execute the get method to get all the issues we copy the detail of an issue we want to modify then let's try out the put endpoint we update the request body now we pass the how we set the id of the issue in the id parameter if i execute the request you can see that it returns a 204 status code let's get all the issues again you can see that the issue has been updated now let's add a method for deleting an issue the method returns an i action result i name it delete it takes an id parameter which represents the id of the issue we want to delete we decorate the method with the http delete attribute the id placeholder specified that the id will be in the url first we check if the issue exists if not we return a not found result as the response otherwise we delete the issue and return a no content result we enhance the documentation with the produce response type attribute we specify that the method can return a 204 status code we also specify that method can also return a 404 status code so let's try the application the new endpoint is shown here let's get the idea of an existing issue then in the delete endpoint we specify the id in the parameter if i execute the request you can see it returns a 204 status code if i get all the issues the one i deleted is gone so that's it for the api now we are going to create an app that will consume the api in the solution add a new project select the template console app then click next give a name to the project i name it tracking.client i leave the dot net 6 as a framework and i click on the create button to generate the project in.net we use the http client class to make http request create a new instance of the http client set the base address property to the url of the api so you can find the address in the launch settings digestion of the api project we also tell the server that we want the result in json format then we are going to retrieve all the issues an instance of http client has methods like get async post async and so on that allows making requests with a certain http verbs we use the get async method to make a get request to the api the method takes the url path of the endpoint and it returns a http response message object we can invoke the ensure success status code to make sure the request succeeds if it is the case we use the content property and invoke the method read from json async to deserialize the content of the response into i innumerable of issue dto so the issue dto is a data transfer object it's similar to the model in the api i'm going to copy all the properties from the model and put it into the detail so then we can iterate over the result to display the title for each issue if there is no issue to display i display a no result message to try out the client we need to run the api first then the client app let's modify the sequence of launch in the solution by enabling multiple startup projects right click on the solution folder then select set startup project then select multiple startup projects tracking api should be first set the action to start tracking client should be second and set the action also to start click on the ok button to apply the changes so now if you click on the start to run the application it will first run the api and then run the console app if you look in the console app you can see the issues from the api and we can also see the same result in the api this concludes this tutorial i hope it was helpful to you if it was please like the video and subscribe for more thanks for watching see you next time
Info
Channel: Tech With Pat
Views: 162,547
Rating: undefined out of 5
Keywords: how to create web api in asp.net core, create a web api with asp.net core and mongodb, create a web api with asp.net core and visual studio 2019, web api with asp.net core, web api asp.net core tutorial, building web api with asp.net core 5, crud web api asp.net core, asp.net core, web api, .net core, crรฉer une API Web avec asp.net core et Visual Studio 2019, tutoriel de base de l'api web asp.net, .net 6, asp.net 6
Id: elMpS1Js7rc
Channel Id: undefined
Length: 33min 3sec (1983 seconds)
Published: Mon Feb 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.