0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Day12. 小さな REST メモ API(FastAPI) - 勝手にChatGPTチャレンジ (Python)

Posted at

前提

本日のお題


12. 小さな REST メモ API(FastAPI)

何を作る?
/memos に POST するとメモが追加され、GET で一覧取得できるだけのミニ Web API。

学べること

  • FastAPI の最小セット(エンドポイント定義・リクエスト / レスポンス)
  • Pydantic モデルでのバリデーション
  • uvicorn でのローカルサーバ起動

面白いところ

  • 後からフロントエンドや他ツールで叩ける「自作 API」が手に入る
  • 簡易的にファイル保存や SQLite を使うなど、バックエンドの入門に最適

回答

準備

pip install fastapi "uvicorn[standard]"

コード

12_rest_memo.py
from typing import List
from datetime import datetime

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field


app = FastAPI(title="Mini Memo API", version="0.1.0")


# ===== Pydantic モデル定義 =====

class MemoCreate(BaseModel):
    """メモ作成時の入力モデル(リクエストボディ)"""
    title: str = Field(..., min_length=1, max_length=100, description="メモのタイトル")
    content: str = Field(..., min_length=1, max_length=1000, description="メモの内容")


class Memo(BaseModel):
    """メモの保存・レスポンス用モデル"""
    id: int
    title: str
    content: str
    created_at: datetime


# ===== 非永続なインメモリストア(実験用) =====

memos: List[Memo] = []
_next_id = 1  # 自動採番用の簡易カウンタ


def _get_next_id() -> int:
    global _next_id
    nid = _next_id
    _next_id += 1
    return nid


# ===== エンドポイント定義 =====

@app.get("/memos", response_model=List[Memo])
def list_memos() -> List[Memo]:
    """
    メモ一覧を取得する。
    """
    return memos


@app.post("/memos", response_model=Memo, status_code=201)
def create_memo(payload: MemoCreate) -> Memo:
    """
    メモを新規作成する。
    """
    memo = Memo(
        id=_get_next_id(),
        title=payload.title,
        content=payload.content,
        created_at=datetime.utcnow(),
    )
    memos.append(memo)
    return memo


@app.get("/memos/{memo_id}", response_model=Memo)
def get_memo(memo_id: int) -> Memo:
    """
    特定のメモを取得する(おまけ機能)。
    """
    for memo in memos:
        if memo.id == memo_id:
            return memo
    raise HTTPException(status_code=404, detail="Memo not found")


@app.delete("/memos/{memo_id}", status_code=204)
def delete_memo(memo_id: int):
    """
    特定のメモを削除する(おまけ機能)。
    """
    for i, memo in enumerate(memos):
        if memo.id == memo_id:
            memos.pop(i)
            return
    raise HTTPException(status_code=404, detail="Memo not found")

実行例

>uvicorn 12_rest_memo:app --reload

# http://127.0.0.1:8000/docs へブラウザからアクセスする

INFO:     Will watch for changes in these directories: ['C:\\Users\\kokekokko\\Documents\\Src\\chatgpt-challenge-python']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [245776] using WatchFiles
INFO:     Started server process [248536]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:56742 - "GET / HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:56742 - "GET /favicon.ico HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:64744 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:64744 - "GET /openapi.json HTTP/1.1" 200 OK
INFO:     127.0.0.1:59060 - "POST /memos HTTP/1.1" 201 Created
INFO:     127.0.0.1:59304 - "GET /memos HTTP/1.1" 200 OK
INFO:     127.0.0.1:63824 - "GET /memos/1 HTTP/1.1" 200 OK
INFO:     127.0.0.1:59879 - "DELETE /memos/1 HTTP/1.1" 204 No Content
INFO:     127.0.0.1:65451 - "GET /memos HTTP/1.1" 200 OK

感想

  • FastAPIを使うと簡単にREST APIを実装できる
  • エンドポイント定義も簡単
  • http://127.0.0.1:8000/docsから簡単に試せるのも良い
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?