ASP.NET Core Web APIs
8 min read
Hello there, Code Traveler! ๐ Welcome to the engine room of the internet.
So far, you might have written C# code that runs in a black console window. It calculates things, prints text, and then... closes. Thatโs cool, but in the real world, software needs to talk to other software. Your mobile app needs to fetch weather data, your website needs to save user profiles, and your smart fridge needs to know if you are out of milk (seriously, why?).
This is where Web APIs come in. Today, we are going to turn your C# logic into a global service accessible by the world.
1. What is a Web API and RESTful Architecture? ๐
The Problem: The Language Barrier
Imagine you have a C# application, a website written in JavaScript, and an iPhone app written in Swift. They all need to share the same database of "Cute Cat Photos."
- The C# app speaks objects and classes.
- The JavaScript app speaks JSON.
- The iPhone app speaks Swift structs.
They are like three people at a dinner party who don't speak the same language. How do they exchange data without chaos?
The Solution: The API (Application Programming Interface)
An API is a mediator. Itโs a set of definitions and protocols that allows one piece of software to talk to another. In the web world, we use Web APIs.
The industry standard for how these APIs should behave is called REST (Representational State Transfer).
The Concept: RESTful Architecture
Definition: REST is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. It typically uses JSON (JavaScript Object Notation) as the common language.
Think of REST as the "Grammar Rules" of the web conversation.
- Client-Server: The Frontend (Client) and Backend (Server) are separate. You can change the code on one without breaking the other, as long as the message format stays the same.
- Stateless: The server doesn't remember the last conversation. Every request must contain all the information needed to complete it. (The server is like Dory from Finding Nemoโ"Hi, I'm a server. Oh look, a request! Hi, I'm a server.")
- Uniform Interface: All API requests look consistent (URLs, HTTP methods).
Fun Fact ๐ฆ: The term "REST" was coined by Roy Fielding in his PhD dissertation in 2000. Imagine writing a homework assignment that dictates how the entire modern internet works 20 years later. Talk about extra credit.
2. Setting Up & Creating Controllers/Routing ๐ฎ
Let's get our hands dirty. We are going to build an API for a "SuperHero Registry".
๐ ๏ธ Industry Standard Setup (The Boilerplate)
We don't manually create files anymore. We use the .NET CLI (Command Line Interface). Open your terminal/command prompt.
# create a new Web API project
dotnet new webapi -n SuperHeroAPI
# Enter the folder
cd SuperHeroAPI
# Open in VS Code (optional but recommended)
code .Note: In .NET 6/7/8/9+, this template uses "Minimal APIs" by default or Controller-based APIs depending on flags. We will focus on Controller-based APIs as they are structurally better for large enterprise applications.
The Problem: Traffic Control
You have a server running. A user sends a request to https://your-site.com/api/heroes. How does the application know which specific C# method should run to handle that URL?
The Solution: Controllers and Routing
Definition: A Controller is a class used to group action methods that handle HTTP requests. Routing is the mechanism that maps the incoming URL to those specific methods.
In ASP.NET Core, a Controller is just a class that inherits from ControllerBase.
Industry Tip ๐ผ: Use
ControllerBase, notController. TheControllerclass adds support for "Views" (HTML pages), which we don't need in an API.ControllerBaseis lighter and faster.
The Code: Your First Controller
Create a file Controllers/SuperHeroController.cs:
using Microsoft.AspNetCore.Mvc;
namespace SuperHeroAPI.Controllers
{
// 1. This attribute tells .NET "This class is an API Controller"
// It enables automatic validation and smart error handling.
[ApiController]
// 2. The Route attribute defines the URL pattern.
// [controller] is a wildcard that gets replaced by the class name (minus "Controller").
// So this becomes "api/SuperHero"
[Route("api/[controller]")]
public class SuperHeroController : ControllerBase
{
// We will add methods here soon!
}
}3. Handling HTTP Requests (The CRUD) ๐ฆ
The Problem: Intent
If a user visits a URL, are they trying to get data, save new data, or delete data? The URL api/heroes looks the same for all of them.
The Solution: HTTP Verbs
We use HTTP Verbs to define the intent of the action. This maps perfectly to CRUD (Create, Read, Update, Delete).
| HTTP Verb | CRUD Operation | Meaning |
|---|---|---|
| GET | Read | "Hey, give me the list of heroes." |
| POST | Create | "Here is a new hero, save them." |
| PUT | Update | "Replace the hero at ID 5 with this new data." |
| DELETE | Delete | "Get rid of this hero." |
Let's flesh out our Controller.
Pre-requisite: Imagine we have a simple class Hero.
public class Hero
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string SuperPower { get; set; } = string.Empty;
}A. GET (Read)
We use [HttpGet] to mark a method for fetching data.
[HttpGet]
public ActionResult<List<Hero>> GetHeroes()
{
var heroes = new List<Hero>
{
new Hero { Id = 1, Name = "Spider-Man", SuperPower = "Webs" },
new Hero { Id = 2, Name = "Iron Man", SuperPower = "Money" }
};
// Returns HTTP 200 OK with the JSON data
return Ok(heroes);
}What happens under the hood: ASP.NET Core automatically takes your C# List, serializes it into JSON text, sets the Content-Type header to application/json, and sends it back. Magic. โจ
B. GET (Read One)
How do we get just one hero? We need a parameter in the URL.
// The "{id}" adds a route parameter. URL: api/SuperHero/5
[HttpGet("{id}")]
public ActionResult<Hero> GetHero(int id)
{
// Imagine we search a DB here.
if (id != 1)
{
// Returns HTTP 404 Not Found
return NotFound("Hero not found. Maybe they are on vacation?");
}
return Ok(new Hero { Id = 1, Name = "Spider-Man", SuperPower = "Webs" });
}C. POST (Create)
Sending data to the server. We expect the data in the Body of the request.
[HttpPost]
public ActionResult<List<Hero>> AddHero([FromBody] Hero newHero)
{
// In real life, save to DB here.
// Returns HTTP 201 Created (Industry Standard for creating things)
return CreatedAtAction(nameof(GetHero), new { id = newHero.Id }, newHero);
}D. PUT (Update) vs DELETE
PUT replaces the whole object.
[HttpPut("{id}")]
public ActionResult UpdateHero(int id, Hero request)
{
// Find hero by id, update properties...
return Ok("Hero Updated!");
}
[HttpDelete("{id}")]
public ActionResult DeleteHero(int id)
{
// Find hero, remove from list...
return Ok("Hero Deleted!");
}Warning โ ๏ธ: Never use a GET request to delete data. Search engines (like Google) crawl links using GET. If you make a "Delete" link accessible via GET, GoogleBot might accidentally wipe your entire database just by browsing your site. That would be a very bad day.
4. Dependency Injection (DI) in ASP.NET Core ๐
This is the concept that separates "Junior" code from "Senior" code.
The Problem: The Hard-Coded Battery
Imagine you are building a toy robot.
- Bad Way: You solder the battery directly inside the robot. If the battery dies or you want to upgrade to a rechargeable one, you have to melt the solder and break the robot to change it.
- Code Equivalent:
var service = new HeroService();inside your controller. Your controller is now "soldered" to that specific service. You can't test the controller without the real service (which might talk to a real DB).
The Solution: Dependency Injection
Definition: DI is a design pattern where a class requests its dependencies from an external source rather than creating them itself.
Analogy: Instead of soldering the battery, you add a Battery Slot. You don't care what battery is put in there (Duracell, Energizer, or a fake test battery), as long as it fits the slot.
How to Implement DI in 3 Steps
Step 1: Create the Interface (The Slot Shape)
public interface IHeroService
{
List<Hero> GetAllHeroes();
}Step 2: Create the Implementation (The Battery)
public class HeroService : IHeroService
{
public List<Hero> GetAllHeroes()
{
return new List<Hero> { /* database logic here */ };
}
}Step 3: Register in Program.cs (The Warehouse)
This tells ASP.NET: "Whenever a controller asks for IHeroService, give them a HeroService."
Open Program.cs:
var builder = WebApplication.CreateBuilder(args);
// ... other config
// Register the service
// We have three lifetimes (Lifetimes are crucial interview questions!):
// 1. AddTransient: Created every time it's requested. (Lightweight)
// 2. AddScoped: Created once per HTTP request. (Most common for DB contexts)
// 3. AddSingleton: Created once and lives forever while the app runs. (Caching)
builder.Services.AddScoped<IHeroService, HeroService>();
var app = builder.Build();Step 4: Inject into Controller (Plug it in)
We use Constructor Injection.
[ApiController]
[Route("api/[controller]")]
public class SuperHeroController : ControllerBase
{
private readonly IHeroService _heroService;
// The container automatically passes the service here!
public SuperHeroController(IHeroService heroService)
{
_heroService = heroService;
}
[HttpGet]
public ActionResult<List<Hero>> Get()
{
// We use the injected service
return Ok(_heroService.GetAllHeroes());
}
}Now your code is:
- Testable: You can inject a fake service for unit tests.
- Maintainable: Change
HeroServicelogic without touching the Controller. - Loose coupled: The controller doesn't know how data is fetched, just that it is fetched.
๐ Resources & References
- Official ASP.NET Core Web API Docs
- Routing in ASP.NET Core
- Dependency Injection in .NET
- HTTP Status Codes (The funny cats version)
Happy Coding! Go build something that talks to the world! ๐
Challenge
Your task is to create a complete ASP.NET Core controller for managing Product resources. This controller must handle all standard CRUD (Create, Read, Update, Delete) operations and follow RESTful principles.
You will be working with a pre-defined Product model and an IProductService interface. Your controller must correctly inject this service to perform data operations.
Requirements:
- Create a class named
ProductsControllerthat inherits fromControllerBase. - Decorate the class with
[ApiController]and a[Route]attribute to map it to the URLapi/products. - Implement a constructor that uses dependency injection to receive an instance of
IProductService. - Implement the following five public action methods:
- GetProducts: A
GETmethod to retrieve all products. It should be mapped to the controller's base route. - GetProduct: A
GETmethod that accepts anint idto retrieve a single product. It should be mapped to"{id}". If the product is not found, it must return aNotFoundresult. - CreateProduct: A
POSTmethod that accepts aProductobject from the request body to create a new product. Upon success, it must return aCreatedAtActionresult, referencing theGetProductaction. - UpdateProduct: A
PUTmethod that accepts anint idfrom the route and aProductobject from the request body to update an existing product. It should return an appropriate success status code. - DeleteProduct: A
DELETEmethod that accepts anint idto remove a product. It should return an appropriate success status code.
- GetProducts: A
Expected result
Your solution should consist of a single C# class, ProductsController.
This class must satisfy the following criteria:
- It must be decorated with the
[ApiController]attribute. - It must have a
[Route]attribute defining the path asapi/products. - It must inherit from
ControllerBase. - It must contain a private readonly field for
IProductService. - It must have a public constructor that accepts an
IProductServiceand assigns it to the private field. - It must contain five public methods, each corresponding to a CRUD operation:
- A
GetProductsmethod with an[HttpGet]attribute, returning anActionResult<IEnumerable<Product>>. - A
GetProductmethod with an[HttpGet("{id}")]attribute, accepting anint id, and returning anActionResult<Product>. This method must handle the case where a product is not found by returningNotFound(). - A
CreateProductmethod with an[HttpPost]attribute, accepting aProductobject, and returning anActionResult<Product>. The return statement should useCreatedAtAction. - An
UpdateProductmethod with a[HttpPut("{id}")]attribute, accepting anint idand aProductobject, and returning anIActionResult(e.g.,NoContent()). - A
DeleteProductmethod with a[HttpDelete("{id}")]attribute, accepting anint id, and returning anIActionResult(e.g.,NoContent()).
- A