Building RESTful APIs with ASP.NET?Core
Image created using Microsoft Designer

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:

  1. Visual Studio 2022?—?https://visualstudio.microsoft.com/downloads
  2. .NET SDK 6.0 or later?—?https://dotnet.microsoft.com/en-us/download/visual-studio-sdks
  3. Microsoft SQL Server Management Studio?—?https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16


Step?—?1: Project?Setup

Follow the steps to create a new project in Visual Studio

  1. Open Visual Studio and click on “Create New Project”
  2. Search for Web API for quick search and then select ASP.NET Core Web API as the project template as shown

Screenshot by author

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)

Screenshot by author

5. Click Create.

You would see a new project has been created in Visual Studio.

Screenshot by author

Step?—?2: Understanding The Project Structure

So this is the project structure that would be created initially after creating a new project

Screenshot by author

We have:

  1. Dependencies?—?Which contains libraries and packages required for the project.
  2. Properties?—?Contains launchSettings.json file containing configuration required for an application to launch such as profiles, environment variables, server settings etc.
  3. Controllers?—?Contains API controllers that handles the incoming HTTP requests.
  4. appSettings.json?—?Stores configuration settings like database connection, logging information.


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:

  1. Right click on your project > Add > New Folder

Screenshot by author

2. Name your folder as Models.

3. Within this Models folder, create a class named Product.

So your project structure should look like this:

Screenshot by author

4. Add few properties in the class that we just created.

Screenshot by author

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.

  1. Install the required NuGet packages:

Open NuGet Package manager from Tools > NuGet Package Manager > Manage Packages for Solution and start installing the packages mentioned below.

2. Search for EntityFrameworkCore

Screenshot by author

3. Next, search for EntityFrameworkCore.SqlServer (highlighted in blue)

Screenshot by author

4. Finally EntityFrameworkCore.Tools

Screenshot by author

5. Create a ProductContext class in Data folder:

Screenshot by author

Inside that class, modify the code like this

Screenshot by author

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

Screenshot by author

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:

Screenshot by author

Follow the steps after this:

  • A pop up will be shown. Type the name of the database you would like to keep.?
  • In our case, it would be ProductDb.?
  • Then click Ok.

Screenshot by author

  • Right click on ProductDb and click Properties.
  • From Server property, copy everything it shows
  • Open your appSettings.json and include the connection string like so:

Screenshot by author

  • After copy everything a bit, a semi-colon is required to terminate the connection string and then we will write the name of database. And finally, Trusted_Connection=True.
  • We also need to register ProductContext in Program.cs to enable dependency injection and configure the database connection for the application.

Dependency Injection is a design pattern to improve flexibility and reducing coupling or more technically “dependency” among?classes.

  • In Program.cs, modify the class to include the code to register the class.

Screenshot by author

We are not done yet. It is now time to create tables using Database First Approach.

  • Right click on Tables and click on Add New Table
  • A table editor will open. Write the table columns as mentioned

Screenshot by author

  • Do not forget to change the table name as highlighted.

Screenshot by author


  • Now click Update button at the top.
  • A pop up will appear?—?simply press “Update Database” and wait for the table to create.
  • If everything goes well, you should see name of the table we just created

Screenshot by author

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.

  • The action method is decorated with [HttpGet("id")]. This means, whichever requests structure contains ID and if it is a get request, would be mapped to GetProduct().
  • Since we want to fetch a single product based on its id, we eliminate IEnumerable and return the ActionResult of Product.
  • The entity framework provides a method FindAsync() which takes id as parameter and the result is stored in product variable.
  • The result is then checked, if not found then NotFound() is returned, otherwise the actual product.

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:

  • The products added would be saved to database using context.
  • The method supports asynchronous operation.

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:

  • Right click on Products table.
  • Click on View Data

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.

要查看或添加评论,请登录

Asp.net with c#的更多文章

社区洞察

其他会员也浏览了