「サーバ - REST API」の版間の差分

ナビゲーションに移動 検索に移動
 
277行目: 277行目:
== APIの基本的な実装 ==
== APIの基本的な実装 ==
==== Python + FastAPIを使用する場合 ====
==== Python + FastAPIを使用する場合 ====
以下に示すソースコードはサーバサイドであり、APIサーバ内部で動作する部分である。<br>
したがって、クライアントが直接触れる部分ではなく、APIサーバの内部実装として機能する。<br>
<br>
クライアントは以下に示すソースコードを意識することなく、定義されたAPIエンドポイントを通じてデータの操作を行うことが可能となる。<br>
<br>
===== PostgresSQLを使用する場合 =====
  <syntaxhighlight lang="python">
  <syntaxhighlight lang="python">
  # main.pyファイル
  # main.pyファイル
296行目: 302行目:
  async def create_item(item: Item):
  async def create_item(item: Item):
     return item
     return item
</syntaxhighlight>
<br>
===== MariaDBを使用する場合 =====
以下の例では、APIサーバがMariaDBと通信するための設定を行う。<br>
* データベースへの接続設定
* コネクションプールの管理
* セッション管理の設定
<br>
<syntaxhighlight lang="python">
# database.py
# SQLAlchemyを使用したデータベース接続設定
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "mysql+mysqlconnector://myapi_user:your_password@localhost/myapi_db"
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_size=5,
    max_overflow=10,
    pool_timeout=30,
    pool_recycle=1800
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
</syntaxhighlight>
<br>
以下の例では、データベースのテーブル構造をPythonのクラスとして定義している。<br>
* データベーステーブルの構造定義
* SQLAlchemyによるORMマッピング
* テーブルのカラム定義とその制約
<br>
<syntaxhighlight lang="python">
# models.py
# モデルの定義例
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.sql import func
from database import Base
class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    description = Column(String(500))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
</syntaxhighlight>
<br>
これらをREST APIサーバとして使用する場合、以下に示すような構成となる。<br>
<syntaxhighlight lang="python">
# main.py (APIエンドポイントの定義)
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from . import models, database
app = FastAPI()
# データベースセッションの依存性注入 (DIコンテナ)
def get_db():
    db = database.SessionLocal()
    try:
      yield db
    finally:
      db.close()
# APIエンドポイント例
@app.post("/items/")
def create_item(name: str, description: str, db: Session = Depends(get_db)):
    db_item = models.Item(name=name, description=description)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item
</syntaxhighlight>
<br>
REST APIサーバの情報を取得する場合は、クライアントからREST APIエンドポイントに対してHTTPリクエストを送信する。<br>
<syntaxhighlight lang="sh">
# クライアントからのAPIリクエスト例
curl -X POST "http://your-server/items/" \
      -H "Content-Type: application/json" \
      -d '{"name": "テスト項目", "description": "説明文"}'
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>


== HTTPS対応 ==
== HTTPS対応 ==

案内メニュー