Introduction
This tutorial will show you how to build a.NET 6 Web API using Entity Framework core, SQL, and API endpoints. This will allow API clients to perform CRUD on data stored in the database.
We will use the database-first approach in our demo application. We will create a table first in the SQL database, and then we’ll use an entity framework for DBContext.
What is Web API?
Web APIs are a platform that allows the development of HTTP services. These services can be accessed from a variety of client-side software, such as mobile phones, web browsers, and desktop programs. It allows multiple applications to interact and exchange data.
Developers can create API functions that are available through HTTP requests. This function allows your clients to access and retrieve specific data that you have made available through the API.
Key features of API
- Supports HTTP verbs such as GET, POST PUT DELETE etc. which allows clients perform different actions on data
- Standard formats such as XML or JSON are supported by default, which helps exchange data between client and server.
- API allows for the definition of custom data, allowing you to customize data according to client requirements
- You can use APIs that are hosted either by yourself or by a third party.
- This allows for easy authentication and authorization, which protects data and helps to control API operations.
- API is the ideal platform to build RESTful web services. These services are flexible, scalable and easy to maintain.
Why do we need Web API?
Today, people use multiple devices, such as smartphones and tablets. To reach all users, you need more than just a web application. An API is needed to expose these data services to the various browsers and apps. By adding a web API, it is easier to connect the two ends and to update.
We need a Web API in this case to manage database interactions and the business logic between an Android app and an iOS application.
The Web API project allows all three applications to communicate with the database. It handles database interactions, and makes sure that the database cannot be accessed directly through websites or applications.
Web APIs are an important tool for modern application development because they allow secure and efficient communication among different devices and applications.
What’s new in .NET 6?
Take a look at the highlights.
Hot reloading
enables developers to make changes to the user interface even while the app is running. The changes are reflected instantly without having to rebuild or restart the application.
Minimal APIs
for developers to build lightweight services without needing templates or controllers, using extension methods of “Endpoint Convention Builder” in the Startup or Program class.
The middleware
logs HTTP request and response data like headers and body to improve debugging.
Blazer
is a web framework that allows you to build interactive web applications using c#. It has improved performance and event binding.
code structure
ASP.NET Core Program and Startup Classes has been simplified.
Support cloud-native
development through integration with Kubernetes or other cloud platforms.
Improved JSON Support
by introducing a new source generation
.NET Core
now supports GraphQL and gRPC APIs The.NET core is more secure thanks to the use of OpenSSL 3 as well as the support for Runtime Defense-in-Depth mitigations.
Supports single-file
applications without extracting for Windows, macOS and Linux
FileStream
has been rewritten to improve performance, particularly for file I/O.
Source code
is now improved with a new framework.
The.NET Runtime
has been improved to include garbage collection improvements, improved performance on ARM-based platforms, and hardware intrinsics.
Entity Frame Core
now supports Cosmos DB, and has a new LINQ query syntax to query nested JSON.
Visual Studio Tooling
has been improved with a new project template and integration with GitHub.
Prerequisites: Web API in .NET 6.0
- Visual Studio 2022.
- .NET SDK 6.0.
- Sql-Server.
Create Project
Enter the project name ProductCrudAPI, select the location where you want to save your project, and click Next.
Select ..Net 6.0 (Long-term support) as a framework. Fill in the required information as shown in the below image, and click on Create.
Select .Net 6.0 (Long-term support) as a framework. Fill in the required information as shown in the below image, and click on Create.
Add NuGet Packages
To use the entity framework core in our project, we need to install two NuGet packages:
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer
Follow the below instructions to install NuGet packages.
Right-click on Dependencies and select Manage NuGet Packages.
Microsoft.EntityFrameworkCore.Tools
Select the Browse tab and search for Microsoft.Entity Frame workCore.Tools and install its latest stable version.
Select.Net 6.0 (Long-term support) as a framework. Fill in the required information as shown
Once the above package is installed, Search for Microsoft.Entity
Frame workCore .SqlServer and
install its latest stable versionMicrosoft.EntityFrameworkCore.SqlServer
Create SQL Database and Table.
Moving to the next section of the Web API in .NET 6.0 Tutorial, create New Database ProductDB in SQL, and execute the below script to create a Product table.
USE [ProductDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Products](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Description] [varchar](250) NULL,
[Price] [decimal](18, 2) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Create DBContext and Model
Now, let’s move on to the next step of our web API tutorial, where we will create the DBContext and Model.
We are using the database first approach of the entity framework.
We have created a database table, and using the Scaffold-DbContext command of the entity framework; we will create the required class in the C# project.
Open Package Manager Console (Tool => Package Manager => Package Manager Console) and run below command:
Scaffold-DbContext “Server=SERVERNAME;Database=ProductDB;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Replace SERVERNAME with your database server name.
Once this command is executed, the Model folder is created in the project solution. Model folder contains two files, ProductDBContext.cs and Product.cs.
ProductDBContext.cs is responsible for database interaction, and Product.cs is a model of the Products table.
Remove OnConfiguring() method from ProductDBContext.cs; it contains a database connection string and is not a good practice. We will add the connection string in the appsettings.json file.
Also remove ProductDBContext() constructor from this file.
Configure DB Connection
Add database connection string in appsettings.json file.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ProductDB": "Server=SERVERNAME;Database=ProductDB;Integrated Security=True;"
}
}
Replace SERVERNAME with your database server name
As we are using the .Net 6 version, we need to make the required configuration changes in the Program.cs file. Microsoft eliminates Startup.cs in .Net 6. In the previous .Net version, Startup.cs was used for configurations.
Add below lines in Program.cs. Please refer to the below image for this.
var connectionString = builder.Configuration.GetConnectionString("ProductDB");
builder.Services.AddDbContextPool(option =>
option.UseSqlServer(connectionString)
);
using Microsoft. EntityFrameworkCore;
using ProductAPI.Models;
Add Products Controller
Add a new empty API controller ProductsController.cs under the controller folder.
Add Methods in ProductsController
In ProductsController.cs, we will add GET, POST, PUT, and DELETE endpoints to achieve CRUD operations.
Please use the below code in your ProductsController.cs.
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProductCRUDAPI.Models;
namespace ProductCRUDAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ProductDBContext _context;
public ProductsController(ProductDBContext context)
{
_context = context;
}
[HttpGet]
public async Task <IEnumerable<Product >> Get()
{
return await _context.Products.ToListAsync();
}
[HttpGet("{id}")]
public async Task <IActionResult> Get(int id)
{
if (id < 1)
return BadRequest();
var product = await _context.Products.FirstOrDefaultAsync(m => m.Id == id);
if (product == null)
return NotFound();
return Ok(product);
}
[HttpPost]
public async Task <IActionResult> Post(Product product)
{
_context.Add(product);
await _context.SaveChangesAsync();
return Ok();
}
[HttpPut]
public async Task <IActionResult> Put(Product productData)
{
if (productData == null || productData.Id == 0)
return BadRequest();
var product = await _context.Products.FindAsync(productData.Id);
if (product == null)
return NotFound();
product.Name = productData.Name;
product.Description = productData.Description;
product.Price = productData.Price;
await _context.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task <IActionResult> Delete(int id)
{
if (id < 1)
return BadRequest();
var product = await _context.Products.FindAsync(id);
if (product == null)
return NotFound();
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return Ok();
}
}
}
Launch API
Finally, we are done with Web API in .NET 6.0 tutorial. Now, it’s time to launch this API, press F5. As we are using Swagger UI, we can execute API directly.
We can see GET, POST, PUT AND DELETE under Products. We can execute different API methods from this page itself.
Finally, we are done with Web API in .NET 6.0 tutorial. Now, it’s time to launch this API, press F5. As we are using Swagger UI, we can execute API directly. We can see GET, POST, PUT AND DELETE under Products. We can execute different API methods from this page itself.