A Web API is a service that accepts HTTP requests and returns data (usually JSON). This is how mobile apps, web frontends, and other services communicate with your backend. Let me show you how to build one from scratch.
Creating the Project
dotnet new webapi -n BookApi
cd BookApi
Defining a Model
First, create a simple class to represent your data:
// Models/Book.cs
namespace BookApi.Models
{
public class Book
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public double Price { get; set; }
public bool IsAvailable { get; set; } = true;
}
}
This is a plain C# class โ nothing fancy. It defines the shape of a book with properties for ID, title, author, price, and availability.
Creating the API Endpoints
Now let us define the endpoints in Program.cs:
using BookApi.Models;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// In-memory data store (replace with a database later)
var books = new List<Book>
{
new Book { Id = 1, Title = "Half of a Yellow Sun", Author = "Chimamanda Ngozi Adichie", Price = 12.99 },
new Book { Id = 2, Title = "Things Fall Apart", Author = "Chinua Achebe", Price = 10.99 },
new Book { Id = 3, Title = "Americanah", Author = "Chimamanda Ngozi Adichie", Price = 14.99 }
};
// GET all books
app.MapGet("/api/books", () => Results.Ok(books));
// GET a single book by ID
app.MapGet("/api/books/{id}", (int id) =>
{
var book = books.FirstOrDefault(b => b.Id == id);
return book is not null ? Results.Ok(book) : Results.NotFound();
});
// POST a new book
app.MapPost("/api/books", (Book book) =>
{
book.Id = books.Max(b => b.Id) + 1;
books.Add(book);
return Results.Created($"/api/books/{book.Id}", book);
});
// DELETE a book
app.MapDelete("/api/books/{id}", (int id) =>
{
var book = books.FirstOrDefault(b => b.Id == id);
if (book is null) return Results.NotFound();
books.Remove(book);
return Results.NoContent();
});
app.Run();
Run the app with dotnet run and test it with a tool like Postman or
curl. You now have a working REST API with CRUD operations.
Testing Your API
# Get all books
curl https://localhost:5001/api/books
# Get a single book
curl https://localhost:5001/api/books/1
# Create a new book
curl -X POST https://localhost:5001/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Purple Hibiscus","author":"Chimamanda Ngozi Adichie","price":11.99}'
# Delete a book
curl -X DELETE https://localhost:5001/api/books/1