Building a Fast and Simple Emoji API using .NET Minimal APIs
Learn how to build a simple Emoji API in .NET 8 Minimal APIs, using a JSON file. The API includes endpoints to get all emojis, search by ID, and filter emojis by name with a flexible "contains" search
dotnet new web -n EmojiApi cd EmojiApi
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Define a model for the emoji data
public class Emoji
{
public string Id { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
// Load the emojis data from the JSON file
List<Emoji> emojis = LoadEmojis();
// Load emojis from the JSON file
List<Emoji> LoadEmojis()
{
var filePath = Path.Combine(AppContext.BaseDirectory, "emojis.json");
var jsonString = File.ReadAllText(filePath);
var emojiList = JsonConvert.DeserializeObject<List<Emoji>>(jsonString);
return emojiList;
}
// Get all emojis
app.MapGet("/emojis", () =>
{
return Results.Ok(emojis);
});
// Get emoji by Id
app.MapGet("/emojis/{id}", (string id) =>
{
var emoji = emojis.FirstOrDefault(e => e.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
return emoji is not null ? Results.Ok(emoji) : Results.NotFound();
});
// Filter emojis by name (contains style search)
app.MapGet("/emojis/filter", (string name) =>
{
var filteredEmojis = emojis.Where(e => e.Name.Contains(name, StringComparison.OrdinalIgnoreCase)).ToList();
return filteredEmojis.Any() ? Results.Ok(filteredEmojis) : Results.NotFound();
});
app.Run();Explanation:
Testing the API:
Note:
PreviousSimplify Configuration Management in .NET: Reading appsettings.json Without Dependency InjectionNextSetting Up a Minimal API in .NET 6.0+ using Console Application
Last updated