Browse the documentation

ASP.NET Core minimal API

The MinimalApi sample is an ASP.NET Core web API whose sources are Typhon modules, with routes, route values, JSON bodies, dependency injection and an async handler.

samples/MinimalApi in the Typhon repository is an ASP.NET Core minimal API written in Typhon. The project uses the ASP.NET Core Web SDK, and its sources are two Typhon modules. main.ty maps the routes to handler functions, and todos.ty holds the data classes and an in-memory store.

Project file

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>$(TyphonTargetFramework)</TargetFramework>
    <TyphonTypeMode>strict</TyphonTypeMode>
  </PropertyGroup>
</Project>

Inside the Typhon repository, TyphonTargetFramework resolves to net11.0, and samples/Directory.Build.props adds the compiler, as for the other samples. Outside the repository, a package reference adds it, as explained in Typhon in a C# project. The sample compiles in strict mode, so every value in it has a static type.

Routes and handlers

An excerpt of main.ty:

import asyncio
import sys
from Microsoft.AspNetCore.Builder import WebApplication
from Microsoft.AspNetCore.Http import IResult, Results
from Microsoft.Extensions.DependencyInjection import *
from todos import NewTodo, Todo, TodoStore


def get_todo(id: int, store: TodoStore) -> IResult:
    todo = store.find(id)
    if todo is None:
        return Results.NotFound()
    return Results.Ok(todo)


def create_todo(body: NewTodo, store: TodoStore) -> IResult:
    todo = store.add(body.title)
    return Results.Created(f"/todos/{todo.id}", todo)


async def slow_square(n: int) -> int:
    """An async handler: a Typhon coroutine is a .NET Task."""
    await asyncio.sleep(0.05)
    return n * n


if __name__ == "__main__":
    builder = WebApplication.CreateBuilder(sys.argv[1:])
    store = TodoStore()
    store.add("Write a minimal API in Typhon")
    builder.Services.AddSingleton(store)
    app = builder.Build()
    app.MapGet("/todos/{id}", get_todo)
    app.MapPost("/todos", create_todo)
    app.MapGet("/square/{n}", slow_square)
    app.Run()

The handlers are plain module functions, passed to MapGet, MapPost and MapPut as values. ASP.NET Core binds their parameters by name and type. id and n come from the route, body: NewTodo from the JSON body of the request, and store: TodoStore from the service container, where AddSingleton registered the store. The handlers return the usual ASP.NET Core results, such as Results.Ok and Results.NotFound, which main.ty imports from Microsoft.AspNetCore.Http like a Python module.

ASP.NET Core calls the handlers, and no Typhon code does, so whole-program type inference sees no call sites for them. Their parameters and return types therefore carry annotations.

slow_square is a coroutine. Typhon compiles it to a method that returns a .NET Task, and ASP.NET Core awaits it like any asynchronous handler.

Data classes and JSON

An excerpt of todos.ty:

from dataclasses import dataclass


@dataclass
class Todo:
    id: int
    title: str
    done: bool


@dataclass
class NewTodo:
    """The body of POST /todos."""
    title: str


class TodoStore:
    """An in-memory store, registered as a singleton service."""

    def __init__(self) -> None:
        self.todos: list[Todo] = []
        self.next_id = 1

    def find(self, id: int) -> Todo | None:
        for todo in self.todos:
            if todo.id == id:
                return todo
        return None

System.Text.Json serializes the Todo dataclass like a C# class, so id, title and done become the properties of the JSON object. The same serializer reads the request body of POST /todos into a NewTodo. find returns Todo | None, which compiles to a nullable reference, and get_todo answers with 404 Not Found when the result is None.

Running the sample

The sample runs as a project with dotnet run, or without the project file with the typhon command:

dotnet run --project samples/MinimalApi -- --urls http://localhost:5000
typhon run samples/MinimalApi/main.ty --urls http://localhost:5000

main.ty imports from Microsoft.AspNetCore, so the typhon command adds the ASP.NET Core framework. typhon build writes the sample as an application that dotnet starts. Native AOT does not support it. The page The typhon command has the details.

These requests were sent to the running sample, one after the other. The responses were the same under dotnet run, under typhon run and from the application built with typhon build:

RequestStatusResponse body
GET /todos200[{"id":1,"title":"Write a minimal API in Typhon","done":false}]
POST /todos with {"title": "Ship it"}201{"id":2,"title":"Ship it","done":false}
PUT /todos/2/done204(empty)
GET /todos/2200{"id":2,"title":"Ship it","done":true}
GET /todos/9404(empty)
GET /square/12200144

With curl, the POST request reads:

curl -X POST -H "Content-Type: application/json" -d '{"title": "Ship it"}' localhost:5000/todos