Python【FastAPI Explained】Build High-Performance APIs with Ease
作成日:2025-11-02
更新日:2025-11-03

🐇 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.)
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.
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)
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.
Interpreter between apps and servers.
Manages the exchange of requests and responses.
Ensures data is transferred safely, accurately, and efficiently.

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
| Name | What it is | Meaning |
|---|---|---|
| API | The rules of communication | The “agreement” |
| API Server | The one who executes the rules | The “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
/hellousing 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 endpointsay_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)
| Name | Meaning | Where It’s Used | Role |
|---|---|---|---|
| Entry Point | Where the app starts running | Inside code (e.g., main()) | The “starting point” of an app |
| Endpoint | Where communication ends inside the server | Web API / FastAPI | The “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
| Example | Meaning |
|---|---|
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
| Role | Analogy | Description |
|---|---|---|
| FastAPI | The car body | The framework — defines the structure and behavior |
| Uvicorn | The engine | Actually 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 --reloadand 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
| Feature | Description |
|---|---|
| High Performance | Built on Starlette and Pydantic, FastAPI handles requests faster than Flask. |
| Type Hints Support | Automatically validates input based on Python type hints — reducing runtime errors. |
| Auto-Documentation | Access /docs to get an automatically generated Swagger UI API page. |
| Asynchronous Processing | Use async def to run database queries or AI calls without blocking other tasks. |
| Modern Architecture | Works 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: APOST /chatrequest 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
| English | Japanese |
|---|---|
| API (Application Programming Interface) | アプリケーション間の通信仕組み |
| Endpoint | APIの入り口となるURL |
| Request / Response | 要求と返答 |
| Async / Await | 非同期処理 |
| Swagger UI | 自動生成されるAPIドキュメント画面 |
| Toolbox / Tool Set | 開発に必要な道具がまとまったセット |
| Starlette | FastAPIの基盤となるネットワーク処理フレームワーク |
| Pydantic | データ型チェック(バリデーション)用ライブラリ |
| Type Hint | Pythonの型注釈 |
| Validation | データの正しさを確認すること |
| Decorator (@) | 関数に特別な機能を付与する仕組み |
| @app.get / @app.post | FastAPIでURLと関数を紐づける記法 |
| Routing | リクエストの行き先を決める仕組み |
| Uvicorn | FastAPIアプリを動かすエンジン(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つを組み合わせて動作している
名前の通り、「速い(Fast)」「使いやすい」「型安全」が特徴
WebアプリやAPIサーバーを作るためのフレームワーク
フレームワークとは
アプリを効率的に作るためのツール群(tool set)
ツール群(tool set)
開発に必要な道具一式のこと。
便利な機能がまとまっている道具箱。
たとえ)料理でいえば…
- ツール群:包丁・まな板・鍋・フライパン(Things)
- 設計思想:レシピ、手順(How To)
道具箱(ツール群)に入っているもの
- リクエストを受け取る仕組み(APIルーティング)
- データを整える仕組み(Pydanticによるバリデーション)
- エラー処理やログ出力
- 自動ドキュメント生成(Swagger UI)
これらの仕組みが最初から入ってる。
アプリを作るとき or APIサーバーを作るときに必要なものが入っている道具箱
APIサーバーとは
APIサーバーとは、アプリとアプリが通信するための窓口。
アプリ ↔︎ サーバーをつなぐ通訳。
リクエストとレスポンスのやり取りを管理する
データを安全・正確・効率的にやり取りする。
APIサーバーがおこなう処理
- リクエストの受付
- 例:
GET /hello
- 例:
- 処理の実行
- 例:AIへの問い合わせやDB検索
- レスポンスの返却
- 例:
{"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システムと外部をつなぐインターフェースとして機能する。
2025-11-02
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[Python]Stringsplit 【Python】文字列を抜き出す|.split -

[Python]Excel datapandas.DataFrame 【Python】シートにあるデータを配列に格納する|pandas.DataFrame -

[Python]inString 【Python】指定の文字列が含まれているか|in -

[Python]Pydantic:The data validation Python【What Is Pydantic?】The Data Validation Engine Behind FastAPI -

[Python]endswith+ lower 【Python】拡張子の存在確認|endswith + lower(Method Chaining) -

[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com