Developing a Basic CRUD API with .NET: A Beginner’s Walkthrough

TemiTope Yusuff
7 min readJun 2, 2023

--

In this post, I will show how to create an API using .NET. This article is for anyone just getting into .NET development, who is a complete beginner.

You do not need to have any previous .NET experience to follow along in this article but it will be good if you have a basic understanding of OOP.

In this guide, we will be creating a Product Management CRUD API using .NET 7.0, this API will allow us create, edit and delete products that will be stored in a database. CRUD basically means Create, Read, Update and Delete.

Here’s the source code for the API.

Before we start, please install the following if you do not have it installed yet

Let’s get started

Step 1: Create a New Project

  • Select create a new project
  • Select ASP.NET Core Web API > Next
  • Name Your Project > Next > Create

Step 2: Setup Database Connection

We will be making use of Microsoft SQL server in this guide, also we will be using Entity Framework to connect to our database as we will be using a code first approach.

First install we install the required NuGet packages which are

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFramework.Tools

Create a new folder “Data” , in this folder create a new class “ApplicationDbContext”

After creating the class, we inherit DbContext from the entity framework library and also create a constructor that takes in an instance of “DbContextOptions<ApplicationDbContext>” as a parameter. The “DbContextOptions” class provides a way to specify various options and settings for the context, such as the database provider, connection string, and other configuration options.

Next, we move to our appsettings.json file and setup our connection strings

  • Server — This specifies the server name or address where the database will be hosted.
  • Database — This specifies the name of the database that the database will be connected to.
  • Trusted_Connection — When set to true this specfies that the connection will use windows authentication and also trusts the credential of the currently logged-in user.
  • TrustServerCertificate — When set to true like we have done this indicates that the client should trust the server certitficate without validation.

Next, we move to our program.cs, where we configure the dependency injection container of our application to include an instance of the ApplicationDbContext class.

Step 3: Create Models

The next step is to create our models, so we create a new folder “Models”.

In the folder “Models”, create a new class “Product.cs”, this class will contain the properties that represent different attributes of a product.

NB: The column type attribute is to specify the precision of the decimal when mapped to the database. In this case, the Amount property will be mapped to a decimal column in the database with a precision of 18 digits and 4 decimal places.

Step 4: Create our table in the database using entity framework

Since, we have previously setup our DbContext the next step is to define a property which is

Using entity framework we are able to create a table named “Products” in our database when we are run our migrations, which is what we will be doing next.

Step 5: Run Migrations and Update Database

Click on the packager manager console in your visual then run this command -

add-migration InitialMigration

If you are using a mac the command is a bit different, so run this instead

dotnet ef migrations add InitialMigration

After this, next is to run the “update-database” command for people using a mac, the command is “dotnet ef database update”.

By doing this and through entity framework thetable “products” is created in our database named “Myfirstdb”.

You can read more on migrations here.

Step 5: Create controllers

There will be no need to create a new folder as there is already for our controllers. Delete the “WeatherForecastcontroller” and then create a new controller called “ProductController”.

Delete the WeatherForecastController
Create a new controller

The controller is going to consist of 5 action methods which are the most basic of a CRUD application.

  • GetProducts — To get all products in the database.
  • GetProduct — To get a single product in the database.
  • CreateProduct — To create a new product and add to the database.
  • EditProduct — To edit/update an existing product.
  • DeleteProduct — To delete a product from the database.

First, before we start writing our methods in the controller, we need to inject our database into the controller. We do this by using a constructor.

Injecting our db into the controller

Now we can go ahead and start creating our methods.

First on the list is the GetProducts action method

The [HttpGet] attribute specifies that this action method should be invoked when an HTTP GET request is made to the corresponding route.

In the method we declare variable products eauals to _context which represents the database context we injected, it then accesses the “Products” property which represents the collection of Product entities in the database, and calls ToList() to retrieve all the products as a list.

Then we return Ok(products), this returns Ok which is an HTTP response and the products as the response body.

Next, Is the GetProduct action method

This is just a bit different to our initial method, this method used to get a particular product. We repeat almost the same steps here as the first method but this time, we use the find method to specify which product to return. The [FromRoute] indicates that the id parameter should be bound from the route value.

Third on our list is the CreateProduct action method

Let’s dissect and understand what is going on in this action method

  • HTTP POST — This attribute specifies that this action method should be invoked when a post request is made
  • (Product product) — This parameter represents the incoming data that should be used to create a new product.
  • var newProduct = new Product () { }; — This creates a new “Product” instance using the values provided in the “product” parameter.
  • _context.Products.Add(newProduct) — This adds the newProduct instance to the _context.Products collection, which represents the table of products in the database.
  • _context.SaveChanges() — This saves the changes to the database.
  • return Ok(newProduct) — This returns the new product as the response body.

Next is the EditProduct action method

This is a bit similar to our Create Product action method but there are few differnces

First, it uses the HTTP PUT attribute

Second, it takes two parameters, one for the id of the product and two for the product

Third, by declaring variable existing product, we first find a product by it’s Id and then if it exists, we are able to be update the product. If not we get a NotFound() response.

The final action method is the Delete Product action method

This action method takes one parameter which is Id and it also uses the HTTP DELETE attribute, we also first get the product we want to delete by it’s id. By using the Remove method we are able to delete the product and then save our changes. Finally we return a message to show that we have been able to delete the product successfully.

Now, that we are done it’s time to test our API, this can be done by clicking the play button in our Visual Studio.

Click on https to test the api

Once you run the api, you should see this and then you can test

Test your api using swwager UI

With that we have come to the end of this guide. I hope you found this helpful.

--

--