Returning JSON
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 2 of 20.
An API answers with data, and the usual format is JSON: text with objects in braces and lists in square brackets. When a lambda returns an object or a list instead of a string, ASP.NET Core writes it as JSON and sets the Content-Type header to application/json. A header is a name and a value sent beside the body.
var books = new List<Book> { new("Dune", 412), new("Emma", 474) };
app.MapGet("/books", () => books);
// at the end of Program.cs, or in its own file, Book.cs:
record Book(string Title, int Pages);GET /books answers [{"title":"Dune","pages":412},{"title":"Emma","pages":474}]. The names start with a lowercase letter because ASP.NET Core writes JSON in camelCase. Every .cs file of a project is compiled together, so a record can live in a file of its own.
Challenge
EasyThe API lists its recipes. A new file, Recipe.cs, holds the Recipe record: record Recipe(int Id, string Name, string Category, int Minutes);.
- In
Program.cs, afterbuilder.Build(), create aList<Recipe>namedrecipeswith these three recipes, in this order:new(1, "Tomato Soup", "soup", 25),new(2, "Pancakes", "breakfast", 15)andnew(3, "Lentil Soup", "soup", 40). - Map
GET /api/recipeswithapp.MapGet. Its lambda returnsrecipes. - Keep
GET /as it is.
Try it: press Run. The first request is GET /api/recipes, and it answers status 200 with a list that starts [{"id":1,"name":"Tomato Soup","category":"soup","minutes":25},. Open the Headers tab: Content-Type is application/json; charset=utf-8. Send GET /: still Recipe API is running, as plain text.
Try it yourself
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Recipe API is running");
app.Run();
All lessons in Minimal APIs
2Results and JSON Bodies
Ok and Not Found