WEB API in ASP.NET CORE MVC | EXPLAIN WEB API IN DEPTH by Shiva Sir

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?

PurposeDescription
🔄 CommunicationEnables frontend and backend apps to communicate using HTTP
⚙️ ReusabilityBackend APIs can be used by web apps, mobile apps, desktop apps
🔐 Centralized Business LogicAll logic is managed on the server side
🚀 Lightweight & FastReturns raw data (JSON), which is faster than rendering views

3️⃣ Web API vs MVC

FeatureMVCWeb API
OutputReturns Views (HTML)Returns Data (JSON/XML)
Use CaseWeb applications (UI required)APIs for mobile, SPA, external systems
Controller TypeControllerApiController
Return TypeIActionResult with ViewActionResult<T> with data

4️⃣ Architecture of Web API in .NET Core

🧱 Layers in a Typical Web API Project:

  1. Model

    • Represents the data structure

    • Example: Student, Product, Employee

  2. Controller

    • Manages API endpoints

    • Handles HTTP requests (GET, POST, PUT, DELETE)

  3. DbContext (Data Access Layer)

    • Entity Framework Core class for database communication

  4. Database

    • SQL Server, PostgreSQL, etc.


🔄 Request Lifecycle:

  1. Client sends an HTTP request → https://api.site.com/products

  2. Router matches the endpoint → ProductController

  3. Action method is called → GetAllProducts()

  4. Data is fetched from the database via DbContext

  5. Data is returned as JSON using Ok(result)

  6. Client (e.g., React app or Postman) receives the JSON response


5️⃣ Key Attributes in Web API

AttributeDescription
[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 TypeDescription
IActionResultBase 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):

MethodActionPurpose
GETReadGet data from server
POSTCreateSend new data to server
PUTUpdateModify existing data
DELETEDeleteRemove 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.

csharp

public StudentController(AppDbContext context) { _context = context; }

🔒 10️⃣ Security in Web API (Basics)

MechanismPurpose
API KeyAuthenticate client requests
JWT (Token)Secure APIs using bearer tokens
HTTPSEncrypts data between client and server
CORSControls 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:

csharp

app.UseAuthentication(); app.UseAuthorization(); app.UseCors();

1️⃣2️⃣ Versioning in Web API (Optional but Useful)

Helps manage changes over time:

csharp

[Route("api/v1/[controller]")] 

[ApiVersion("1.0")] 

EXAMPLE OF API:

🔧 Step-by-Step Implementation:


✅ Step 2: Create Project

  1. Open Visual Studio

  2. Create a new project → ASP.NET Core Web API

  3. Name: StudentAPI

  4. Choose .NET 6/7 → Click Create


✅ Step 3: Create Student Model


public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Course { get; set; } }

✅ Step 4: Create DbContext

Install EF Core packages:


Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools

Now, create AppDbContext.cs:


public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Student> Students { get; set; } }

✅ Step 5: Configure Database Connection

In appsettings.json:


"ConnectionStrings": { "DefaultConnection": "Server=.;Database=StudentDB;Trusted_Connection=True;" }

In Program.cs:


builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddControllers();

✅ Step 6: Create Student Controller

Controllers/StudentController.cs


[ApiController] [Route("api/[controller]")] public class StudentController : ControllerBase { private readonly AppDbContext _context; public StudentController(AppDbContext context) { _context = context; } // GET: api/student [HttpGet] public async Task<ActionResult<IEnumerable<Student>>> GetAll() { return await _context.Students.ToListAsync(); } // GET: api/student/1 [HttpGet("{id}")] public async Task<ActionResult<Student>> Get(int id) { var student = await _context.Students.FindAsync(id); if (student == null) return NotFound(); return student; } // POST: api/student [HttpPost] public async Task<ActionResult<Student>> Create(Student student) { _context.Students.Add(student); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(Get), new { id = student.Id }, student); } // PUT: api/student/1 [HttpPut("{id}")] public async Task<IActionResult> Update(int id, Student student) { if (id != student.Id) return BadRequest(); _context.Entry(student).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } // DELETE: api/student/1 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var student = await _context.Students.FindAsync(id); if (student == null) return NotFound(); _context.Students.Remove(student); await _context.SaveChangesAsync(); return NoContent(); } }

✅ Step 7: Run Migrations and Update DB


Add-Migration InitialCreate Update-Database

This creates the StudentDB database and Students table.


✅ Step 8: Test API Using Postman

Base URL: https://localhost:5001/api/student

OperationHTTP VerbURLBody (if needed)
Get All StudentsGET/api/student
Get by IDGET/api/student/1
CreatePOST/api/studentJSON: {"name":"Aman","age":21,"course":"C#"}
UpdatePUT/api/student/1JSON: updated values
DeleteDELETE/api/student/1

🏁 Final Structure:


StudentAPI/ │ ├── Controllers/ │ └── StudentController.cs │ ├── Models/ │ └── Student.cs │ ├── Data/ │ └── AppDbContext.cs │ ├── appsettings.json └── Program.cs

🧠 Is Web API REST or SOAP?

Short Answer:

A Web API can be either REST or SOAPit 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:

TypeDescription
REST APIMost common. Uses HTTP verbs (GET, POST, etc.), returns JSON or XML, stateless.
SOAP APIOlder, strict protocol. Uses XML, defined by WSDL, uses POST only.
GraphQL APIModern alternative to REST, client controls the data shape.
gRPC APIHigh-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.


✅ Summary Table:

AspectREST API (Web API)SOAP API (WCF)
FormatJSON (or XML)XML only
ProtocolHTTP/HTTPSHTTP, SMTP, TCP
FlexibilityLightweight, easy to consumeHeavy, strict standards
Common in .NETASP.NET Core Web APIWCF (Windows Communication Foundation)
ToolingWorks with Postman, browser, JSNeeds SOAP clients (WSDL)

Post a Comment

0 Comments