C# Foundations·C# from first file to first API

A minimal ASP.NET API

Map endpoints, validate input and return accurate HTTP responses.

Beginner 15 min read Lesson 10 of 300 Challenge included
What you will be able to do
  • Use Results<Ok<T>, NotFound, BadRequest> to make outcomes explicit.
  • Bind request bodies to records; do not accept an unbounded dictionary.
  • Add authentication and rate limiting before exposing writes.

In plain English

ASP.NET minimal APIs are a small, explicit way to expose JSON. Bind only the data you need, validate it, return typed results and keep authorization on the server. The same patterns scale from a demo to a maintained service.

Program.csC#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/api/courses", async (AppDb db) =>
    Results.Ok(await db.Courses.ToListAsync()));

app.MapPost("/api/courses", async (CourseInput input, AppDb db) =>
{
    if (string.IsNullOrWhiteSpace(input.Title))
        return Results.BadRequest(new { error = "INVALID_TITLE" });

    var course = new Course(Guid.NewGuid(), input.Title, input.Lessons);
    db.Courses.Add(course);
    await db.SaveChangesAsync();
    return Results.Created("/api/courses/" + course.Id, course);
});

app.Run();
Your turn

Validate a course title

Medium

Return 400 with an INVALID_TITLE error when the title is empty; return 201 otherwise.

CSHARP · starter
app.MapPost("/api/courses", async (CourseInput input, AppDb db) =>
{
    db.Courses.Add(new Course(input.Title));
    await db.SaveChangesAsync();
});
Check your understanding before moving on.
Knowledge checkQuestion 1

Which result is appropriate after creating a resource?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 10 of 300 · 0% of course