liveBook · Manning

FastAPI

As explained in Domain-Specific Small Language Models

A Python web framework for building APIs with automatic documentation, asynchronous request handling, and data validation support.

FastAPI is a Python framework for building web APIs. It combines type hints, asynchronous request handling, and validated data models with automatically generated interactive API documentation. Its role in model serving is to expose inference behind HTTP routes. section 11.2

A basic FastAPI service follows a small operational pattern:

  • Create an app, then define URL routes with decorated Python functions that handle HTTP requests. section 11.2
  • Start the server from the command line; set its host and port as needed. Interactive documentation is available at /docs and /redoc. section 11.2
  • For model inference, define request fields with Pydantic and connect a route to the generation function. section 11.2.2
from fastapi import FastAPI

app = FastAPI()

@app.post("/generate")
async def generate_text(request: GenerateRequest):
    device = "cpu"
    generated_sentence = await generate(request.prompt,
                                        request.max_length,
                                        device)

    return {"Generated sentence = ": generated_sentence}

This route accepts a validated prompt and length, calls an asynchronous generation function on the CPU, and returns the generated text. section 11.2.2

In the ONNX example, the generation function prepares model inputs, runs inference, and decodes the output. Asynchronous handling lets the CPU do other work while inference completes; network conditions and output size can also affect request latency. section 11.2.2

How Domain-Specific Small Language Models covers it

How deep it goes
Moves from app setup and routes to server startup, validation, and an ONNX inference endpoint.
Examples
Uses GET and POST routes, interactive API docs, and a CPU-hosted GPT-2 small ONNX generation endpoint.
What you can do after
Build from scratch: define routes and validated request data, start a server, and expose model generation through an API.
How it connects
Connects routes and type hints with Starlette, Pydantic, ONNX Runtime, and Hugging Face pipelines.

Also explained in

Compare how 5 books explain FastAPI →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Domain-Specific Small Language Models. The section links point to the parts of the book it draws on.