Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

minimal-api

БесплатноБез исполняемых скриптовНе проверен

Minimal APIs on .NET 10, the default for HTTP endpoints: one IEndpoint per feature with MapModules/MapEndpoints discovery, TypedResults, endpoint filters…

codewithmukeshот codewithmukesh★ 858 звёзд на GitHub

Об этом скилле

Minimal APIs (.NET 10)

Core Principles

  1. Minimal APIs are the default. Use controllers only when migrating legacy code. Minimal APIs are lighter, faster, and compose well with any architecture style.
  2. One IEndpoint per feature, discovered by convention. Each feature folder has one endpoint class. Program.cs calls one discovery method (app.MapModules() in a modular app, app.MapEndpoints() in a single project) and never changes when features are added.
  3. Return TypedResults unions. Results<Created<T>, ProblemHttpResult> gives compile-time checking and correct OpenAPI documentation without .Produces() calls. Results.Ok(value) and IResult give neither.
  4. Metadata over comments. .WithName(), .WithSummary() and XML comments on request/response records feed the OpenAPI document.

Patterns

One IEndpoint per Feature (Required Pattern)

The endpoint is a thin adapter: route, authorization, OpenAPI text, and a call to the feature's handler. The full interfaces (IEndpoint, IHandler, IModule) and discovery code are in skills/modular-slices/references/building-blocks.md.

public interface IEndpoint
{
    void Map(IEndpointRouteBuilder endpoints);
}
// Features/PlaceOrder/PlaceOrderEndpoint.cs
internal sealed class PlaceOrderEndpoint : IEndpoint
{
    public void Map(IEndpointRouteBuilder endpoints) =>
        endpoints.MapPost("/", HandleAsync)
            .RequirePermission(OrdersPermissions.Manage)
            .WithName("PlaceOrder")
            .WithSummary("Places an order");

    private static Task<Results<Created<OrderResponse>, ProblemHttpResult>> HandleAsync(
        PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) =>
        handler.HandleAsync(request, ct);
}

In a modular app, MapModules() maps every module's endpoints under /api/v1/{module}, tags them with the module name, and adds the validation filter, so the route above is relative to the module group:

// Program.cs (modular): never changes when features are added
builder.AddModule<CatalogModule>();
builder.AddModule<OrdersModule>();

var app = builder.Build();
app.MapModules();

In a single-project app, one scan does the same job:

public static IEndpointRouteBuilder MapEndpoints(this IEndpointRouteBuilder app)
{
    var api = app.MapGroup("/api")
        .AddEndpointFilterFactory(RequestValidation.Create)
        .ProducesValidationProblem();

    foreach (var type in typeof(Program).Assembly.GetTypes()
                 .Where(t => t is { IsClass: true, IsAbstract: false } && typeof(IEndpoint).IsAssignableFrom(t))
                 .OrderBy(t => t.FullName, StringComparer.Ordinal))
        ((IEndpoint)Activator.CreateInstance(type)!).Map(api);

    return app;
}

Endpoints are sorted by name so routes and the OpenAPI document come out in the same order on every build.

TypedResults Unions for Type-Safe Responses

The handler's return type is the endpoint's HTTP contract. Errors are ProblemDetails with a stable code built by the Problems helper (see the error-handling skill).

internal sealed class GetOrderHandler(OrdersDbContext db) : IHandler
{
    public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
    {
        var order = await db.Orders.AsNoTracking()
            .Where(o => o.Id == id)
            .Select(o => new OrderResponse(o.Id, o.ProductId, o.Quantity, o.Total, o.PlacedAt))
            .FirstOrDefaultAsync(ct);

        return order is null ? Problems.NotFound() : TypedResults.Ok(order);
    }
}

Returning a result type that is not in the union is a compile error, and OpenAPI documents 200 and the problem response automatically.

Parameter Binding

.NET 10 minimal APIs bind parameters from route, query, header, body, and DI automatically.

// Route parameters
endpoints.MapGet("/{id:guid}", (Guid id, GetOrderHandler handler, CancellationToken ct) => handler.HandleAsync(id, ct));

// Query parameters (nullable = optional)
endpoints.MapGet("/", (int page, int? pageSize, string? status) => ...);

// Complex query parameters with [AsParameters]
public sealed record ListOrdersQuery(int Page = 1, int PageSize = 20, string? Status = null);
endpoints.MapGet("/", ([AsParameters] ListOrdersQuery query, ListOrdersHandler handler, CancellationToken ct) => ...);

// Header binding (FromHeader needs using Microsoft.AspNetCore.Mvc;)
endpoints.MapGet("/", ([FromHeader(Name = "X-Correlation-Id")] string? correlationId) => ...);

// DI services (including handlers) are resolved without an attribute
endpoints.MapPost("/", (PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) => ...);

Endpoint Filters

Filters are the minimal API equivalent of action filters. Use them for cross-cutting concerns like validation, logging, and idempotency checks.

Validation uses one filter factory on the t

Полный SKILL.md на GitHub

Установить minimal-api в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/api-versioning.md

FAQ

Что делает скилл minimal-api?

Minimal APIs on .NET 10, the default for HTTP endpoints: one IEndpoint per feature with MapModules/MapEndpoints discovery, TypedResults, endpoint filters, parameter binding, API versioning (Asp.Versioning). Use for "endpoint", "MapGet", "MapGroup", "IEndpoint", "API versioning". Do NOT use for OpenAPI documents or Scalar (use openapi), module and project layout (use modular-slices) or throttling (use rate-limiting).

Как установить скилл minimal-api?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл minimal-api запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить minimal-api с