How to create a Web API with ASP.NET Core | C# tutorial for beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will learn how to create a web api using asp.net core and c-sharp by the end of the video you will be able to create an api that supports creating reading updating and deleting data my name is pat if you are new to the channel consider subscribing let's get into it the api we are going to create will be able to manage books we will expose various endpoints for creating reading updating and deleting books this handpoint will be used in combination with an http verb to perform specific action on the data in case you want to follow along i will use visual studio 2019 and the net 5 sdk let's launch visual studio and then select create a new project on the next screen select the asp.net core web application and then next in this dialog we'll give a name to the project let's name it book api and then click create in this dialog select asp.net core web api then click on create to generate all the project files well done the project is created let's remove two files we wanted weather forecast at the root of the project and weather forecast controller in the controllers folder behind the rest api we will use entity framework to interact with a sqlite database entity framework is an object relational mapper it allows working with a database using dotnet object instead of sql statement let's start by installing a nuget package named microsoft dot entity framework car dot sqlite this package has everything that helps work with entity framework and sqlite using entity framework core data access is performed using a model we need to create a book model let's create a folder named models then add a new class name book this class has few properties id which is a unique identifier the title represents the title of the book author is the name of well the author description is a short description of the book in the real world a book has probably more attributes than this entity framework core also need a context object the context object allows querying and saving data in the model folder let's add a new class called book context this class inherits from the db context class the constructor takes a db context option object as parameter this object is a configuration of the context it will be injected through dependency injection let's also expose a dbset property that represents a collection of books let's make sure the database is created when using the db context once the book context is created we need to register it for dependency injection let's update the configure services method in the startup.css file we use the add db context to register the book contextclass with asp.net course dependency injection system we also provide a connection string to the sqlite database which is a simple file in our project if you have an existing database this is the place where you can set your connection string entity framework is all set it's time to add a repository simply put a repository is a layer that sits between our application and the data access layer which is in our case the book context adding a repository is a good practice it helps adding a layer of abstraction between your code and the data access layer let's create a folder name repositories then we add an interface called ibook repository this interface describes operation that can be performed against the database yet we'll retrieve all books get with id parameter will retrieve a single book create update and delete our self-explanatory let's add a concrete implementation in the repositories folder we add a new class called book repository this class implements the ibook repository interface the repository will query the database using the book context we inject the context through the constructor let's implement the create method we use the add method of the db set to add a new instance of the book class the save changes async method we insert data into the database in the delete method we use the remove method of the db set and the save changes async will delete the entity from the database let's implement the get method now inviting the to list async on the db set will fetch all the books from the database the holder get method takes an id parameter we will use the find by idsync method to get a single book the last method is the update method we change the state of the entity and the save changes async will update the entity in the database the repository is ready now we need to register it with the dependency injection system let's update the configure service method in the startup.cs file add sculpt will register an instance of the book repository this also means that only one instance of the book repository class will be created for a given http request the repository is ready let's create an api controller an api controller is a class that is responsible for handling requests for an endpoint right click on the controllers folder next add the controller then select api controller empty we name the class books controller let's take a look at the structure of the controller it has a route attribute that defines the path that the controller will handle in our case the path will be api books the api controller attribute provide behavior such as automatic model validation and more the controller inherits from controller base which provides many property and method that are useful for handling http requests the controller needs an instance of the book repository to interact with the database let's inject the book repository in the constructor now let's implement method that are going to handle specific http requests this method are called action method we will create one for each http verb we want to handle let's create a new method called getbooks this method returns an i enumerable of book we decorate the method with the http get attribute this tells asp.net that the method will handle http get requests we get the books from the repository using the get method when this action is invoked asp.net will convert the book's object to json before returning it to the caller let's create a new method also named getbooks this method returns a task of action result of a book object why can we just return a book object the taskbar is because the caller will be able to await this method the action results provide the flexibility to return other types like not found or bad requests for instance the method takes an id as a parameter it also decorated with the http get to tell that it will handle http get request notice that the http get in the attribute is used with an argument in curly braces this puts the endpoint sub path in the id parameter if we use api slash books slash the number 3 for instance then the id parameter will f3 as a value we get a single book from the repository using the get method that takes an id let's run the project to test what we've done so far as you can see the default page comes with documentation of the api the template we use to create the project comes with open api support this give us swagger ui which is a tool that generate documentation for our api it also supports testing the api in the browser let's try the get endpoint if i execute it of course there is no data because our database is empty let's add a breakpoint inside the actions getbooks if i execute the getendpoint again as you can see the breakpoint in the first gatebook method is hit let's do the same with the second get i provide a random id and if i execute the breakpoint is also hit the endpoint seems to work let's implement an action method to posting a book in the controller we add a new method called past books the method takes a book object in parameter and returns a task of action result of book we decorate the method with the http pos attribute to tell that it will handle http pass requests thanks to a process called model binding asp.net will convert a json in the request payload to a book object we use the create method on the repository to insert a book in the database we return a create action result which will generate 201 http status code let's run the project to test this endpoint select post in the request body we add a json text this json represents a book we set some properties we execute if we check the result we get a 201 http status code let's add another book and execute now let's test the get endpoint if i execute i got the two books i post now let's add an action method to update an existing book we add a new method called putbooks it returns a task of action result it takes an id parameter which is the id of the book we want to update it also takes a book parameter which is the updated books it is decorated with the http put to tell that it will handle http put request we make sure that the id provided in the url and the one in the payload is the same otherwise we return a bad request result body requests generate four or http status code which indicates that the server cannot understand the request if the id is okay we invoke the update method of the repository we return a no content result that will generate 201 http status code to indicate that the request has been processed but there is no data let's test this endpoint let's first execute a get so we can copy a book payload now in the put endpoint i set the id to 2 paste the payload i modify the description if i execute a request if i execute the get endpoint again you can see that the description has been changed let's implement the action method for deleting a book we add a new method called delete books the method takes an id parameter which is the id of the book we want to delete it return a task of action result we decorate it with an http delete attribute to tell that it will handle http delete requests we first check if the book exists in the database if the book exists we invoke the remove method from the repository to delete it finally we return a no content result let's test the endpoint i provide the id 2 which is the id of the second book and i hit execute if i execute the get end point as you can see the second book is no longer there that's it for this tutorial if you enjoy it feel free to like the video and subscribe to the channel thanks for watching see you soon you
Info
Channel: TechWithPat
Views: 69,913
Rating: 4.9397511 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 2.0, 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, création d'une API Web avec asp.net core 2.0
Id: sWJayOop4k8
Channel Id: undefined
Length: 16min 24sec (984 seconds)
Published: Wed Jan 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.