Last active
December 22, 2022 21:35
-
-
Save martijn/406b809721935fe261749f0f69a6f0dd to your computer and use it in GitHub Desktop.
Expose a JSON dataset as an HTTP API with minimal C# code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Author
martijn
commented
Dec 22, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment