Hot Posts

Module 3

Document

Great 👍 we’ve completed:
✅ Module 1: .NET Core & ASP.NET
✅ Module 2: ASP.NET MVC

Now let’s move to:


✅ Module 3: Web API

3.1 What is Web API?

  • Definition: ASP.NET Web API is a framework to build RESTful HTTP services that can be consumed by different clients like browsers, mobile apps, or other applications.

  • Works with JSON or XML data.

  • Can be hosted inside ASP.NET Core apps or standalone.


3.2 REST Principles

A Web API usually follows REST (Representational State Transfer) principles:

  1. Stateless → Each request is independent (no session).

  2. Resource-based → Everything is treated as a resource (/students/1).

  3. HTTP Methods used properly:

    • GET → Read data

    • POST → Insert new data

    • PUT → Update existing data

    • DELETE → Remove data

  4. Uniform Interface → Consistent URL structure.


3.3 MVC Controller vs API Controller

Feature MVC Controller API Controller
Purpose Returns HTML Views Returns data (JSON/XML)
Return Type ViewResult JsonResult, Ok(), NotFound()
Use Case Web applications Mobile apps, SPAs, external services

3.4 Creating a Web API in .NET Core

  • Step 1: Create Controller


[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAllStudents()
    {
        var students = new List<string> { "John", "Mary", "David" };
        return Ok(students);
    }
}
  
  • Step 2: Use Postman or Browser to test → GET /api/student


3.5 CRUD Operations in Web API


[HttpGet("{id}")]
public IActionResult GetStudent(int id) => Ok(new { Id = id, Name = "Test" });

[HttpPost]
public IActionResult AddStudent([FromBody] Student s) => Created("", s);

[HttpPut("{id}")]
public IActionResult UpdateStudent(int id, [FromBody] Student s) => Ok(s);

[HttpDelete("{id}")]
public IActionResult DeleteStudent(int id) => NoContent();
  

3.6 Status Codes in Web API

  • 200 OK → Success.

  • 201 Created → Resource created.

  • 204 No Content → Deleted successfully.

  • 400 Bad Request → Invalid input.

  • 404 Not Found → Resource not found.

  • 500 Internal Server Error → Exception occurred.


3.7 Securing Web API

  • Basic Authentication → Username/password.

  • Token-based (JWT) → Recommended.

  • Example: Authorization: Bearer <token> in headers.


3.8 Versioning in Web API

  • Useful when API changes but old clients still need old version.

  • Example:

    • /api/v1/student

    • /api/v2/student


📌 Summary for Module 3:

  • Web API = RESTful service returning JSON/XML.

  • Must know CRUD operations, status codes, difference between MVC vs Web API, and security basics.

  • Must know CRUD operations, status codes, difference between MVC vs Web API, and security basics.