Building RESTful APIs with ASP.NET?Core
Step-By-Step Implementation For Beginners
APIs have become an important part of web and mobile development process. ASP.NET Core, introduced by Microsoft is the best choice to create fast, secure and scalable APIs.
In this article, I will walk you through how we can build RESTful APIs with ASP.Net Core.
Table Of?Contents
· What We Will Be Building? · Prerequisites · Step?—?1: Project Setup · Step?—?2: Understanding The Project Structure · Step?—?3: Creating A Model · Step?—?4: Setting Up a Database Context · Step?—?5: Configuring the Database Connection
What We Will Be Building?
We will build RESTful API to create a new product, retrieve all products or just a specific product, update or delete a product.
Prerequisites
Before we make a start, ensure you have following things setup:
Step?—?1: Project?Setup
Follow the steps to create a new project in Visual Studio
3. Click Next and you will be asked to name your project. Give a name. select the desired path where you wish to store your project into, and then click ‘Next’.
4. Once you click ‘Next’ you will asked to select the Framework. For now we will select the default selection i.e.?.NET 8.0 (Long Term Support)
5. Click Create.
You would see a new project has been created in Visual Studio.
Step?—?2: Understanding The Project Structure
So this is the project structure that would be created initially after creating a new project
We have:
Step?—?3: Creating A?Model
Model in ASP.NET Core application represents the data and business logic of the application.
It basically defines the classes (i.e. structure of data) and properties within that class.
So now follow the steps:
2. Name your folder as Models.
3. Within this Models folder, create a class named Product.
So your project structure should look like this:
4. Add few properties in the class that we just created.
Next, we will set up database context.
Step?—?4: Setting Up a Database?Context
We would be using Entity Framework Core to make interactions with database.
Open NuGet Package manager from Tools > NuGet Package Manager > Manage Packages for Solution and start installing the packages mentioned below.
2. Search for EntityFrameworkCore
3. Next, search for EntityFrameworkCore.SqlServer (highlighted in blue)
4. Finally EntityFrameworkCore.Tools
5. Create a ProductContext class in Data folder:
Inside that class, modify the code like this
Don’t forget to inherit DbContext class.?
If you are getting error in DbContextOptions, you need to import using Microsoft.EntityFrameworkCore in your class.?
The DbSet of type Product would create a table named Product in database.
Step?—?5: Configuring the Database Connection
In Visual Studio, go to View > SQL Server Object Explorer
The above explorer will open on to your left of the screen.
Next, right click on Databases and then select New Database, like shown below:
Follow the steps after this:
Dependency Injection is a design pattern to improve flexibility and reducing coupling or more technically “dependency” among?classes.
We are not done yet. It is now time to create tables using Database First Approach.
Step?—?6: Creating the Controller
This step would be a little bit detailed one, so I would breaking them down in subtitles so you can understand them easily.
Moreover, we will write our code first and then see it’s output at the end.
To create a controller, right click on Controllers folder > Add > Controller as shown:
Next, it would ask you to select the scaffolding template. Select MVC Controller?—?Empty
On the next popup, without selecting any option, simply rename the controller to ProductsController.cs` and then click Add.
You would be presented with this:
Remove the Index() and follow the sub-steps after creating the controller
领英推荐
a) Adding Controller And Routing Attributes
Try to add the following code and I will tell what’s going on with that code later
As you can see, the ProductsController` is decorated with something inside square brackets.
The ApiController indicates that the controller would be used to handle HTTP API requests.
The [Route(ap/controller) serves as the base URL route for the controller. It’s like the mapping?—?which ever request meant for ProductsController matches the format api/controller would be redirected to ProductsController.
b) Dependency Injection via Constructor
In this step, we would enable the controller to access and interact with database context i.e., _context` to manage the product related data.
The instance of ProductContext` is injected into ProductsController` through its constructor.
c) Retrieving Products Using ‘HttpGet’
In order to retrieve the available products, we would create a new action method in this controller called GetProducts() which will fetch all the available products.
The method would be marked as [HttpGet]. With this, we are telling the controller:
Whichever request matches the signature of api/products, would be mapped to GetProducts()
Write this method exactly after the constructor that you wrote in step b)
So, what’s happening here?
We have used asynchronous programming, hence async and await keyword because we don’t to block the execution of the processed going on.
Every controller has an ActionResult as a return type of controller actions that represents the result of an action method.?
It is required because it provides flexibility to return either a specific data type or an HTTP response.
Finally, we are returning the list of products from _context` as a form of list.
d) Retrieving Specific Products Using Its?‘Id’
What if you want to fetch a specific product instead of all of them??—?Yes, you can fetch it by its id. And this is how you do it:
Something similar to GetProducts() but here are some key differences.
e) Creating A New?Product
In APIs, you can create a new product using [HttpPost] decorator.
The explanation for the method structure is pretty much the same, so not going to repeat it over here. You can see the same structure in most of the API controller action method.
What you need to understand here is that EntityFramework provides SaveChangesAsync() method which means that:
f) Updating A?Product
The HttpPut decorator would handle all the update requests for ProductController.
First we have checked if the Id that we want to update and the id in our Product table matches.
Flagging that product state to be modified?—?telling EntityFramework that the request is a modification request.
Save all the changes using SaveChangesAsync().
If something happens to be an issue, it is handled in catch.?
g) Removing A?Product
This would be our final step?—?removal a product means completely removing the data regarding that product from the database.
The Remove() would accept the product that we wish to remove and SaveChangesAsync() would update the database with latest values without the one that we have just removed.
Step?—?7: Running the Application
All coding done! It’s now time to run the application.
Creating A New Product Using?Swagger
In visual studio, ensure you have “http” option selected as startup project?
and then simply press Ctrl + F5.
Swagger will open in your browser. If you want to change the browser, you can go to Web Browser > select the desired web browser you wish to you.
This is the initial screen that would get?
Since we don’t have any products, let’s first create them and then see if our API is working correctly.
Expand the POST accordion in Swagger > Click on Try It Out. In case if you are wondering where is the this option:
Try to add sample data as directed below.
Why have we used Id, Name, Price and Description??—?That’s because our Product` model contains these properties.
Click on Execute at the bottom and see if you are getting this output:
You will see two status codes: 200 and 201.
Status code 200 means the request was fulfilled and the requested data was returned.
Status code 201 means anew resource was created in response to a request. In our case, a new product was created.
Viewing Our Product In?Swagger
Again click on Try It Out and then click on Execute.
You should see the data we just created.
You can also see this in our SQL Server Database.
To do so, head on to Visual Studio and follow these steps:
Hurray!! If you’ve come along until this step successfully, pat yourself on back because you’ve just created and retrieved a product using our API!
Updating A Product In?Swagger
In update operation, we will expand the HttpPut accordion in Swagger.
Mention the id in the Id textbox and try to update some value as shown below:
It is important to note that you must mention all the attributes that you used to create one.
Here we are trying to update the name of the product and price. Earlier the name of product was Wireless Mouse, after update it is Logitech Wireless Mouse.?
And the price was 499 which is now updated to 299.
Hit execute and then see if you are getting the desired result.
Deleting A Product In?Swagger
To delet a product, expand HttpDelete` according in Swagger and enter the Id of the product you wish to delete.
Since we have just one product, we will enter its id which 1 and then hit Execute
With this, we have completed all the basic operations with RESTful APIs.
Unfortunately, I am not able to use Code First Approach due to technical issues?—?but I will bring another version of article where I will explain the same stuff with Code First Approach?—?trust me its fun!
Ending Note
If you have come along these steps and congratulations! We have successfully built a RESTful API using ASP.NET Core.
ASP.NET Core’s grip in performance and scalability is exceptional and you can easily extend this API to meet various application requirements.
Happy coding!
Was This Article Helpful????
If you found this article helpful and if you feel I was able to help you with concepts of ASP.Net Core, Swagger and RESTful APIs, please show your appreciation with some claps as much as you can.
Feel free to leave a comment below with your thoughts, experiences, or any additional tips on setting boundaries.