銀河鉄道

Python【FastAPI Explained】Build High-Performance APIs with Ease

サムネイル
[Python]Learn FastAPIStep by Step

🐇 Part 1 — What is FastAPI?

FastAPI Overview

FastAPI is a toolbox for building APIs that are fast, safe, and easy.
It’s lightweight, high-performance, and designed with type safety to help you avoid mistakes.

(Note: FastAPI runs on two powerful bases — Starlette for network communication and Pydantic for data validation.)

FastAPI is:

A lightweight framework for building APIs quickly and safely.

So, what exactly is a framework?

What is a “Framework”?

A framework is a set of tools that helps you build apps efficiently.
It’s like a well-organized toolbox packed with everything you need for development.

Framework is:

A toolkit for building apps efficiently.

In cooking terms:

  • Tools: knife, cutting board, pan, pot — the physical tools
  • Design philosophy: recipe, steps — the logical process

Frameworks combine both — tools and a consistent way of thinking.

So you don’t have to reinvent everything from scratch.

What’s inside the toolbox?

  • Request handling (API routing)
  • Data validation (via Pydantic)
  • Error handling & logging
  • Automatic documentation (Swagger UI)

In short:

FastAPI is a toolbox filled with everything you need to build an app or an API server.

So, what exactly is a API Server?

What is an API Server?

An API server is a gateway that allows applications to communicate with each other.

An API server

Interpreter between apps and servers.

Manages the exchange of requests and responses.

Ensures data is transferred safely, accurately, and efficiently.

Generated by ChatGPT

What does an API server actually do?

  • Receive a request
    e.g. GET /hello
  • Run a process
    e.g. Query the database or call an AI model
  • Return a response
    e.g. {"message": "Hello!"}

FastAPI lets you implement this request–process–response flow simply and efficiently.

API vs. API Server

NameWhat it isMeaning
APIThe rules of communicationThe “agreement”
API ServerThe one who executes the rulesThe “executor”

So far:

FastAPI = A framework (toolbox) for building API servers easily and safely.

🐇 Part 2 — FastAPI in Action

Example: The Basic Structure of FastAPI

Let’s create a simple API that returns a “Hello!” message when you access /hello.

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello!"}

That’s all you need to get started with a working API.

So, what exactly is the “@” in @app.get ?

What does @app.get mean?

The @ symbol is called a decorator — it’s like giving a function a special sticker that says,
“Hey, this function has extra powers!”

In this case, @app.get("/hello") tells FastAPI:

“Register this function as an endpoint for the URL /hello using the GET method.”

Without it, FastAPI wouldn’t know which URL should call which function.

So, what exactly is an endpoint ?

What Is an “Endpoint”?

An endpoint is the final destination of communication — the receiving point on the server.
In other words, it’s where a request from an app or browser finally arrives.

Communication Flow

Client — the sender of a request.
Examples: browsers, mobile apps, or JavaScript’s fetch() function.

Server — the receiver of a request.
Frameworks like FastAPI, Django, or Flask run here.

Endpoint — the place inside the server that decides which function to execute.
Identified by a combination of URL and HTTP method (e.g., GET, POST).

Example

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello, world!"}

Here:

  • /hello → is the endpoint
  • say_hello() → is the function (handler) connected to that endpoint

So when a client sends:

curl http://localhost:8000/hello

FastAPI looks for the say_hello() handler registered at /hello, executes it,
and returns its result as a response.

Endpoint vs Entry Point (Structure Comparison)

NameMeaningWhere It’s UsedRole
Entry PointWhere the app starts runningInside code (e.g., main())The “starting point” of an app
EndpointWhere communication ends inside the serverWeb API / FastAPIThe “end point” of communication

Why It’s Called an “End”

“End” literally means the point where something finishes.
In the API world, it refers to the arrival point of communication — the receiving door of the server.

So:

  • From the client’s perspective → it’s like a door
  • From the server’s perspective → it’s like the inside of the doorway (arrival point)

Meanwhile, the entry point is the opposite —
it’s where the application says, “Alright, let’s start running!”

Extra: Relationship to REST APIs

  • Endpoint → the address of the API, published as a URL
  • REST API → the rule set that defines how HTTP is used

So, you can think of endpoints as the address book of a REST API.

Regular Function vs Decorator

Normal function:

def say_hello():
    return {"message": "Hello!"}

With a decorator:

@app.get("/hello")
def say_hello():
    return {"message": "Hello!"}

Under the hood, this:

app.get("/hello")(say_hello)

means the same thing — it applies the route definition to your function.

Analogy: Decorating a Recipe

ExampleMeaning
def say_hello():The recipe itself
@app.get("/hello")A sticker that says “Display this recipe in the dessert section”

So when you “decorate” a function, FastAPI understands where and how it should be used.

Summary of Decorators

  • @ = a marker that adds configuration or functionality to a function
  • In FastAPI, decorators tell the app which URL and HTTP method the function belongs to
  • Example:
    • @app.get("/hello") → for GET requests
    • @app.post("/chat") → for POST requests (sending data)

Running FastAPI

Running with Uvicorn

To run a FastAPI app, you need Uvicorn — the engine that actually makes it move.

Example:

uvicorn main:app --reload

Meaning of each part

  • uvicorn → the command
  • main → the file name (main.py)
  • app → the FastAPI instance created in the code
  • –reload → auto-restart when the code changes (useful in development)

Analogy: FastAPI and Uvicorn = Car and Engine

RoleAnalogyDescription
FastAPIThe car bodyThe framework — defines the structure and behavior
UvicornThe engineActually runs the app, receives requests, returns responses

Technically Speaking

Uvicorn is an ASGI server (Asynchronous Server Gateway Interface)
a Python standard that allows asynchronous communication between apps and clients.

FastAPI fully supports ASGI, so Uvicorn is required to run it.

Running the App

Once you run:

uvicorn main:app --reload

and open http://127.0.0.1:8000/hello in your browser,
you’ll get this response:

{"message": "Hello!"}

That’s it — your first FastAPI app is live

🐇 Part 3 — Key Features & Use Cases of FastAPI

Key Features of FastAPI

FeatureDescription
High PerformanceBuilt on Starlette and Pydantic, FastAPI handles requests faster than Flask.
Type Hints SupportAutomatically validates input based on Python type hints — reducing runtime errors.
Auto-DocumentationAccess /docs to get an automatically generated Swagger UI API page.
Asynchronous ProcessingUse async def to run database queries or AI calls without blocking other tasks.
Modern ArchitectureWorks beautifully with Clean Architecture and RAG (Retrieval-Augmented Generation) designs.

Practical Use Cases

  • AI APIs: Implement an endpoint that sends a question to an LLM and returns its answer.
    Example: A POST /chat request sends text to an AI model and returns the response.
  • RAG Systems: Act as the external interface (API layer) that connects the Retrieval and Generation modules.

In short, FastAPI is perfect as a bridge between AI logic and the outside world.

Vocabulary List

EnglishJapanese
API (Application Programming Interface)アプリケーション間の通信仕組み
EndpointAPIの入り口となるURL
Request / Response要求と返答
Async / Await非同期処理
Swagger UI自動生成されるAPIドキュメント画面
Toolbox / Tool Set開発に必要な道具がまとまったセット
StarletteFastAPIの基盤となるネットワーク処理フレームワーク
Pydanticデータ型チェック(バリデーション)用ライブラリ
Type HintPythonの型注釈
Validationデータの正しさを確認すること
Decorator (@)関数に特別な機能を付与する仕組み
@app.get / @app.postFastAPIでURLと関数を紐づける記法
Routingリクエストの行き先を決める仕組み
UvicornFastAPIアプリを動かすエンジン(ASGIサーバー)
ASGI (Asynchronous Server Gateway Interface)非同期通信を可能にするPythonサーバー規格
Command Line (CLI)ターミナル操作インターフェース
–reloadコード変更を自動検知して再起動
Server / Clientサーバー=応答側 / クライアント=要求側
Middlewareリクエストとレスポンスの間に挟まる共通処理層
Clean Architecture層ごとに責務を分離する設計手法
RAG (Retrieval-Augmented Generation)検索+生成を組み合わせたAI構成

Summary

FastAPI is not just a framework — it’s a developer-friendly environment that lets you build modern, safe, and high-speed APIs with clarity and confidence.
Whether you’re connecting to AI models, creating microservices, or designing data pipelines, FastAPI gives you the right balance of simplicity and power.

FastAPIとは

FastAPIは、APIを “速く・安全に・楽に” 作るための道具箱。

軽くて速く、型安全でミスを防ぐ設計。

※ 補足: Starlette(通信処理)とPydantic(データ検証)の2つを組み合わせて動作している

FastAPI

名前の通り、「速い(Fast)」「使いやすい」「型安全」が特徴

WebアプリAPIサーバーを作るためのフレームワーク

フレームワークとは

フレームワーク

アプリを効率的に作るためのツール群(tool set)

ツール群(tool set)

開発に必要な道具一式のこと。
便利な機能がまとまっている道具箱。

たとえ)料理でいえば…

  • ツール群:包丁・まな板・鍋・フライパン(Things)
  • 設計思想:レシピ、手順(How To)

道具箱(ツール群)に入っているもの

  • リクエストを受け取る仕組み(APIルーティング)
  • データを整える仕組み(Pydanticによるバリデーション)
  • エラー処理ログ出力
  • 自動ドキュメント生成(Swagger UI)

これらの仕組みが最初から入ってる。

PythonのFastAPI

アプリを作るとき or APIサーバーを作るときに必要なものが入っている道具箱

APIサーバーとは

APIサーバーとは、アプリとアプリが通信するための窓口。

APIサーバー

アプリ ↔︎ サーバーをつなぐ通訳。

リクエストとレスポンスのやり取りを管理する

データを安全・正確・効率的にやり取りする。

APIサーバーがおこなう処理

  1. リクエストの受付
    • 例:GET /hello
  2. 処理の実行
    • 例:AIへの問い合わせやDB検索
  3. レスポンスの返却
    • 例:{"message": "Hello!"}

FastAPIは、この「受付・処理・返却」をシンプルかつ高速に実装できるフレームワーク。

用語整理)API と APIサーバー

名前正体つまり
APIやりとりのルール約束
APIサーバールールを実行する人約束を実行する

コード例:FastAPIの基本構造

from fastapi import FastAPI

たとえば /hello にアクセスしたときに「Hello!」というメッセージを返すAPIを作る場合

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello!"}

@ は デコレーター(decorator)

@ は「この関数に特別な機能を付与する印」。

通常の関数の場合

def say_hello():
    return {"message": "Hello!"}

デコレーターを使う場合

FastAPIで「この関数は /hello というURLで呼び出せるようにしたい」と伝える場合、
その設定を上に付与するために使うのが @app.get("/hello")

つまり、「この関数を /hello に対応するAPIエンドポイントとして登録する」という宣言になる。

@app.get("/hello")
def say_hello():
    return {"message": "Hello!"}

このコードは内部的には以下と同じ意味を持つ。

def say_hello():
    return {"message": "Hello!"}

app.get("/hello")(say_hello)

@app.get("/hello")app.get("/hello") を関数に適用するショートカット記法

たとえ)シールを貼ること

例え意味
def say_hello():レシピの本体
@app.get("/hello")「このレシピはデザートコーナーに並べる」とシールを貼る

このシール(@)を貼ると、
FastAPIが「この関数はどのURLで呼ばれるか」を理解できる。

デコレータのまとめ

@ は「関数に設定や機能を装飾(decorate)する記号」。
FastAPIでは「この関数がどのURLと対応するか」を指定するために使う。

例えば @app.post("/chat") と書けば、それは「POSTメソッド(データを送信するリクエスト)」用のエンドポイントになる。

FastAPIを動かす

uvicornで実行する

uvicornとは

FastAPIアプリを動かすためのエンジン

たとえば、このmain.pyを実行するなら

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello!"}

↓ ターミナルで uvicorn

uvicorn main:app --reload

各要素の意味

  • uvicorn → 実行コマンド
  • main → ファイル名(main.py の “main”
  • app → FastAPIで定義したアプリ名
  • --reload → コードを保存すると自動で再起動(開発中に便利)

例)「FastAPIとUvicorn」= 「車とエンジン」

役割たとえ説明
FastAPI車の本体アプリの中身や仕組みを作る部分
Uvicornエンジンそのアプリ(車)を実際に動かす。リクエストを受け取り、レスポンスを返す

技術的に言うと

UvicornはASGIサーバー(Asynchronous Server Gateway Interface)。
→「Python製のWebアプリ」が「ブラウザ・スマホ」と通信できるようにする仕組み」。

FastAPIはASGIに対応している
そのため、Uvicorn(=アプリを動かす役)が必須。

uvicornで実行する

FastAPIはアプリの本体であり、Uvicornはそれを動かすエンジン。
Uvicornを使って、ブラウザで http://127.0.0.1:8000/hello にアクセスすると
JSONレスポンス({"message": "Hello!"})が返ってくる。

FastAPIの特徴

特徴内容
高速処理StarletteとPydanticを利用することで、Flaskよりも高速に動作する。
型ヒント対応Pythonの型ヒントを使うことで自動的に入力チェックが行われる。
自動ドキュメント/docs にアクセスするだけでSwagger UIが自動生成される。
非同期処理対応async def を用いることで、AI処理やDB通信をノンブロッキングで実行できる。
モダン設計Clean ArchitectureやRAG構成などとの親和性が高い。

FastAPIの利用例

  • LLMに質問を送るためのAPIエンドポイントの実装
    例: /chat にPOSTで質問を送信すると、AIが返答を返す構造
  • RAG構成における「外部公開層(API)」として機能
    RetrievalやGeneration層と連携して動作する

FastAPIは、AIシステムと外部をつなぐインターフェースとして機能する。

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧