Skip to content

Instantly share code, notes, and snippets.

@martijn
Last active December 22, 2022 21:35
Show Gist options
  • Save martijn/406b809721935fe261749f0f69a6f0dd to your computer and use it in GitHub Desktop.
Save martijn/406b809721935fe261749f0f69a6f0dd to your computer and use it in GitHub Desktop.
Expose a JSON dataset as an HTTP API with minimal C# code
using System.Text.Json;
var jsonDocument = JsonSerializer.Deserialize<JsonElement>("""
{
"Germany": { "Population": 83783942, "Language": "German" },
"France": { "Population": 65273511, "Language": "French" },
"the Netherlands": { "Population": 17134872, "Language": "Dutch" }
}
""");
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Return full jsonDocument for the root URI
app.MapGet("/", () => Results.Json(jsonDocument));
// Return a single object or string for URIs like /Germany or /France/Language
// or a 404 if the specified path does not exist
app.MapGet("/{*path}", (string path) =>
{
try
{
var result = path.Split("/").Aggregate(
jsonDocument,
(jsonElement, pathSegment) => jsonElement.GetProperty(pathSegment));
return Results.Json(result);
}
catch (Exception ex) when (ex is KeyNotFoundException or InvalidOperationException)
{
return Results.NotFound();
}
});
app.Run();
@martijn
Copy link
Author

martijn commented Dec 22, 2022

$ curl -i "http://localhost:5107/France/Language"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

"French"
$ curl -i "http://localhost:5107/Germany"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"Population":83783942,"Language":"German"}
$ curl -i "http://localhost:5107/Mexico"
HTTP/1.1 404 Not Found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment