Web API  

Working with Web APIs in ASP.NET Core

1. What is a Web API?

A Web API enables applications to communicate over HTTP using data formats such as JSON.

In ASP.NET Core, Web APIs are commonly used to:

  • Serve data to frontend apps (React, Angular, mobile apps)

  • Connect systems together

  • Build backend services

Key idea:
Client sends a request → API processes it → API sends a response

2. Creating a Web API Project

ASP.NET Core provides built-in support for APIs using controllers.

Main parts you’ll see:

  • Controllers – handle requests

  • Models – represent data

  • Endpoints – URLs clients call

3. Example: Simple Products API

Step 1: Product Model

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

This represents the data sent and received as JSON.

Step 2: API Controller

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static List<Product> products = new()
    {
        new Product { Id = 1, Name = "Laptop", Price = 1200 },
        new Product { Id = 2, Name = "Mouse", Price = 25 }
    };

    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(products);
    }

    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        var product = products.FirstOrDefault(p => p.Id == id);
        if (product == null)
            return NotFound();

        return Ok(product);
    }
}

Pause and think

What do you think [HttpGet] does here?

4. Calling the API

If the app is running, you can call:

  • GET /api/products → returns all products

  • GET /api/products/1 → returns one product

The response is JSON, like:

{
  "id": 1,
  "name": "Laptop",
  "price": 1200
}

5. Why Use ASP.NET Core for APIs?

  • Fast and lightweight

  • Built-in dependency injection

  • Easy JSON handling

  • Cross-platform

Quick Check (answer one )

What part of this feels most confusing right now?

  • Controllers

  • Routes

  • HTTP methods (GET, POST, etc.)

  • The overall flow