1️⃣ What is Web API?
🔹 Definition:
A Web API (Web Application Programming Interface) is a set of HTTP endpoints exposed by a server application that allows other applications (frontend, mobile, etc.) to communicate over the web.
In .NET Core, a Web API is a type of controller that returns data (usually JSON), not views (HTML).
2️⃣ Why Use Web API?
| Purpose | Description |
|---|---|
| 🔄 Communication | Enables frontend and backend apps to communicate using HTTP |
| ⚙️ Reusability | Backend APIs can be used by web apps, mobile apps, desktop apps |
| 🔐 Centralized Business Logic | All logic is managed on the server side |
| 🚀 Lightweight & Fast | Returns raw data (JSON), which is faster than rendering views |
3️⃣ Web API vs MVC
| Feature | MVC | Web API |
|---|---|---|
| Output | Returns Views (HTML) | Returns Data (JSON/XML) |
| Use Case | Web applications (UI required) | APIs for mobile, SPA, external systems |
| Controller Type | Controller | ApiController |
| Return Type | IActionResult with View | ActionResult<T> with data |
4️⃣ Architecture of Web API in .NET Core
🧱 Layers in a Typical Web API Project:
-
Model
-
Represents the data structure
-
Example:
Student,Product,Employee
-
-
Controller
-
Manages API endpoints
-
Handles HTTP requests (GET, POST, PUT, DELETE)
-
-
DbContext (Data Access Layer)
-
Entity Framework Core class for database communication
-
-
Database
-
SQL Server, PostgreSQL, etc.
-
🔄 Request Lifecycle:
-
Client sends an HTTP request →
https://api.site.com/products -
Router matches the endpoint →
ProductController -
Action method is called →
GetAllProducts() -
Data is fetched from the database via
DbContext -
Data is returned as JSON using
Ok(result) -
Client (e.g., React app or Postman) receives the JSON response
5️⃣ Key Attributes in Web API
| Attribute | Description |
|---|---|
[ApiController] | Specifies the class is a Web API controller. Adds automatic model validation and behavior |
[Route()] | Defines the URL path to reach the action method |
[HttpGet] | Handles GET requests |
[HttpPost] | Handles POST (create) requests |
[HttpPut] | Handles PUT (update) requests |
[HttpDelete] | Handles DELETE requests |
6️⃣ Return Types in Web API
| Return Type | Description |
|---|---|
IActionResult | Base type for any HTTP response |
ActionResult<T> | Strongly typed return data (like ActionResult<Student>) |
Ok(data) | Returns 200 OK with data |
NotFound() | Returns 404 |
BadRequest() | Returns 400 |
CreatedAtAction() | Returns 201 with location header |
7️⃣ RESTful API Principles
Web APIs in .NET Core follow REST principles (REpresentational State Transfer):
| Method | Action | Purpose |
|---|---|---|
| GET | Read | Get data from server |
| POST | Create | Send new data to server |
| PUT | Update | Modify existing data |
| DELETE | Delete | Remove data |
8️⃣ Entity Framework Core in Web API
-
EF Core is the ORM used to map C# objects to database tables.
-
Benefits:
-
Write LINQ instead of SQL
-
Manage migrations
-
Easy CRUD with
DbSet<T>
-
9️⃣ Dependency Injection
-
Web API uses Dependency Injection (DI) to manage services like
DbContext. -
Automatically injects services into controllers.
🔒 10️⃣ Security in Web API (Basics)
| Mechanism | Purpose |
|---|---|
| API Key | Authenticate client requests |
| JWT (Token) | Secure APIs using bearer tokens |
| HTTPS | Encrypts data between client and server |
| CORS | Controls which frontend apps can access your API |
1️⃣1️⃣ Middleware in Web API
-
Middlewares are used to process requests/responses.
-
Example: Authentication, Logging, Exception handling
In Program.cs:
1️⃣2️⃣ Versioning in Web API (Optional but Useful)
Helps manage changes over time:
[)]
EXAMPLE OF API:
🔧 Step-by-Step Implementation:
✅ Step 2: Create Project
-
Open Visual Studio
-
Create a new project → ASP.NET Core Web API
-
Name:
StudentAPI -
Choose .NET 6/7 → Click Create
✅ Step 3: Create Student Model
✅ Step 4: Create DbContext
Install EF Core packages:
Now, create AppDbContext.cs:
✅ Step 5: Configure Database Connection
In appsettings.json:
In Program.cs:
✅ Step 6: Create Student Controller
Controllers/StudentController.cs
✅ Step 7: Run Migrations and Update DB
This creates the StudentDB database and Students table.
✅ Step 8: Test API Using Postman
Base URL: https://localhost:5001/api/student
| Operation | HTTP Verb | URL | Body (if needed) |
|---|---|---|---|
| Get All Students | GET | /api/student | — |
| Get by ID | GET | /api/student/1 | — |
| Create | POST | /api/student | JSON: {"name":"Aman","age":21,"course":"C#"} |
| Update | PUT | /api/student/1 | JSON: updated values |
| Delete | DELETE | /api/student/1 | — |
🏁 Final Structure:
🧠 Is Web API REST or SOAP?
✅ Short Answer:
A Web API can be either REST or SOAP — it depends on how the API is designed.
🔍 Let’s Understand:
🔹 Web API
-
A general term for any API that can be accessed using the web (HTTP/HTTPS).
-
It is a technology-neutral term.
-
It could be implemented using REST, SOAP, GraphQL, gRPC, etc.
✅ Common Types of Web APIs:
| Type | Description |
|---|---|
| REST API | Most common. Uses HTTP verbs (GET, POST, etc.), returns JSON or XML, stateless. |
| SOAP API | Older, strict protocol. Uses XML, defined by WSDL, uses POST only. |
| GraphQL API | Modern alternative to REST, client controls the data shape. |
| gRPC API | High-performance, binary-based, good for microservices. |
📌 Example in .NET Core:
-
If you create a Web API using ASP.NET Core, it's by default a RESTful Web API.
-
Uses
[ApiController], routes like/api/products, and returns JSON. -
Uses HTTP methods like GET, POST, PUT, DELETE.
-
-
If you want to create a SOAP-based API, you would use WCF (Windows Communication Foundation) — not Web API.
Entity Framework Core Code First Example (Department & Employee)
This example demonstrates a Code First approach in .NET 8/9 Entity Framework Core with the following constraints:
✅ Primary Key
✅ Foreign Key
✅ NOT NULL
✅ Maximum Length
✅ Required Fields
✅ Default Value
✅ Unique Constraint
✅ Check Constraint
✅ One-to-Many Relationship
Project Structure
Models
│
├── Department.cs
├── Employee.cs
│
Data
│
└── AppDbContext.cs
Department Entity
using System.ComponentModel.DataAnnotations;
public class Department
{
[Key]
public int DepartmentId { get; set; }
[Required]
[StringLength(100)]
public string DepartmentName { get; set; } = string.Empty;
[StringLength(250)]
public string? Description { get; set; }
public ICollection<Employee> Employees { get; set; }
= new List<Employee>();
}
Employee Entity
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Employee
{
[Key]
public int EmployeeId { get; set; }
[Required]
[StringLength(100)]
public string EmployeeName { get; set; } = string.Empty;
[Required]
[EmailAddress]
[StringLength(150)]
public string Email { get; set; } = string.Empty;
[Required]
[StringLength(15)]
public string MobileNo { get; set; } = string.Empty;
[Required]
[Column(TypeName = "decimal(18,2)")]
public decimal Salary { get; set; }
[Required]
public DateTime JoiningDate { get; set; }
public bool IsActive { get; set; }
//-------------------------
// Foreign Key
//-------------------------
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; } = null!;
}
AppDbContext
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees => Set<Employee>();
public DbSet<Department> Departments => Set<Department>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//---------------------------------
// Department
//---------------------------------
modelBuilder.Entity<Department>()
.HasIndex(x => x.DepartmentName)
.IsUnique();
//---------------------------------
// Employee
//---------------------------------
modelBuilder.Entity<Employee>()
.HasIndex(x => x.Email)
.IsUnique();
modelBuilder.Entity<Employee>()
.Property(x => x.IsActive)
.HasDefaultValue(true);
modelBuilder.Entity<Employee>()
.HasCheckConstraint("CK_Employee_Salary",
"Salary >= 10000");
//---------------------------------
// One-To-Many Relationship
//---------------------------------
modelBuilder.Entity<Employee>()
.HasOne(e => e.Department)
.WithMany(d => d.Employees)
.HasForeignKey(e => e.DepartmentId)
.OnDelete(DeleteBehavior.Restrict);
}
}
Connection String
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=CompanyDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Register DbContext
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection"));
});
Create Migration
Add-Migration InitialCreate
or
dotnet ef migrations add InitialCreate
Update Database
Update-Database
SQL Generated by EF Core (Equivalent)
Department Table
CREATE TABLE Departments
(
DepartmentId INT IDENTITY(1,1) PRIMARY KEY,
DepartmentName NVARCHAR(100) NOT NULL UNIQUE,
Description NVARCHAR(250) NULL
)
Employee Table
CREATE TABLE Employees
(
EmployeeId INT IDENTITY(1,1) PRIMARY KEY,
EmployeeName NVARCHAR(100) NOT NULL,
Email NVARCHAR(150) NOT NULL UNIQUE,
MobileNo NVARCHAR(15) NOT NULL,
Salary DECIMAL(18,2) NOT NULL
CHECK(Salary>=10000),
JoiningDate DATETIME2 NOT NULL,
IsActive BIT NOT NULL DEFAULT(1),
DepartmentId INT NOT NULL,
CONSTRAINT FK_Department
FOREIGN KEY(DepartmentId)
REFERENCES Departments(DepartmentId)
)
Insert Sample Data
var department = new Department
{
DepartmentName = "IT",
Description = "Software Development"
};
_context.Departments.Add(department);
await _context.SaveChangesAsync();
var employee = new Employee
{
EmployeeName = "Shiva",
Email = "shiva@gmail.com",
MobileNo = "9876543210",
Salary = 60000,
JoiningDate = DateTime.Now,
DepartmentId = department.DepartmentId
};
_context.Employees.Add(employee);
await _context.SaveChangesAsync();
Retrieve Data with LINQ
var employees = await _context.Employees
.Include(e => e.Department)
.ToListAsync();
foreach (var emp in employees)
{
Console.WriteLine($"{emp.EmployeeName} - {emp.Department.DepartmentName}");
}
Relationship Diagram
Department
+------------------------------+
| DepartmentId (PK) |
| DepartmentName (UNIQUE) |
| Description |
+------------------------------+
|
| One
|
|
Many
+------------------------------+
| EmployeeId (PK) |
| EmployeeName |
| Email (UNIQUE) |
| MobileNo |
| Salary |
| JoiningDate |
| IsActive |
| DepartmentId (FK) |
+------------------------------+
Constraints Used
Constraint Example
Primary Key EmployeeId, DepartmentId
Foreign Key DepartmentId → Departments.DepartmentId
NOT NULL [Required]
Maximum Length [StringLength(100)]
Unique HasIndex(...).IsUnique()
Default Value HasDefaultValue(true)
Check Constraint Salary >= 10000
One-to-Many One Department → Many Employees

0 Comments
POST Answer of Questions and ASK to Doubt