So far, Kladde.Web serves only the prototype pages from wwwroot, and only the console knows the Kladde’s data. In this module, the
Kladde gets a web API: endpoints that don’t return pages but data as JSON, for programs instead of people. The Blazor pages from
module 2.5, tests and, later, other services talk to it. By the end of the module, the API can create, read, change and delete contacts
and appointments, checks its input, reports errors by the standard and describes itself.
In this first lesson, you get to know the structure of an ASP.NET Core application, start it in different ways and build the Kladde’s first endpoint. It returns the contacts from the same JSON file your console from K1 writes, and not a single line of the core changes for it.
The smallest web API
This module’s exercises are file-based apps again, in the folder k2-practice next to the Kladde’s repository, as in lesson 2.1.1.
Create a subfolder 2-3 there and in it the file hello-api.cs:
// hello-api.cs: the smallest web API
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello from the Kladde!");
app.Run();
You know the two lines with #: from lesson 2.1.1: The first makes the file a web app, the second turns off the preparation for native
AOT. Without that line, no types of your own would come out as JSON, only 500. Start the app:
dotnet run hello-api.cs
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Users\ada\k2-practice\2-3
The app is running now and waits for requests until you press Ctrl+C in the terminal. From a second terminal, send a request:
curl -i http://localhost:5000/
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
Hello from the Kladde!
Every real response also contains a Date: line with the date and time. The outputs in this module leave it out, because yours will be
different anyway.