0
0

サクッと API を作ろう|FastAPI, Hugging Face,Docker,Python

Last updated at Posted at 2024-04-06

はじめに

API として提供することで、アプリケーションへの統合が容易になります。この記事では、FastAPI と Hugging Face を使用して、シンプルな API を素早く構築し、デプロイする方法を紹介します。
Google Croud Runを試行錯誤しましたが、うまくできませんでした。hugging faceならさくっとできました。

前提条件

  • Hugging Face のアカウントを持っていること

手順

ステップ 1: サンプルの Hugging Face Space を複製する

  1. Hugging Face にログインします。
  2. https://huggingface.co/spaces/tregu0458/FastapiSample にアクセスします。
  3. ページ右上の "Duplicate this Space" ボタンをクリックします。
  4. "Duplicate Space" ダイアログが表示されたら、新しい Space の名前を入力し、"Space visibility" を選択して、"Duplicate Space" ボタンをクリックします。
  5. 複製した Space のページにリダイレクトされます。

ステップ 2: 複製した Space を編集する

  1. 複製した Space のページで、"Files" タブをクリックします。
  2. main.py ファイルをクリックして、コードを編集します。
  3. 必要に応じてコードを変更し、"Commit changes" ボタンをクリックして保存します。

ステップ 3: API ドキュメントを見る

  1. "enbed This space"から、URLをひらく
  2. 例えば、https://huggingface.co/spaces/tregu0458/FastapiSample
  3. 例えば、https://huggingface.co/spaces/tregu0458/FastapiSample\docsを開く
    1. APIドキュメントがみられる

ステップ 4: 必要に応じて API を拡張する

  1. main.py ファイルを編集して、新しいエンドポイントを追加したり、既存のエンドポイントを変更したりします。
  2. 変更をコミットし、Space をアップデートします。
  3. 更新された API をテストします。

まとめ

この記事では、Hugging Face Spaces にあるサンプルの FastAPI アプリケーションを複製し、編集してデプロイする方法を紹介しました。この手順を応用して、独自の API として提供することができます。FastAPI と Hugging Face を組み合わせることで、シンプルかつ効率的に API を構築し、デプロイすることが可能です。

参考資料

Docker
FROM python:3.10.9

COPY . .

WORKDIR /

RUN pip install --no-cache-dir --upgrade -r /requirements.txt

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py
from fastapi import FastAPI

app = FastAPI(title="Deploying FastAPI Apps on Huggingface")

@app.get("/", tags=["Home"])
def api_home():
    return {'detail': 'Welcome to FastAPI Tutorial!'}

@app.post("/",tags=["hello"])
def hello(name: str):
    return {'message': f"hello {name}!"}
requirements.txt
fastapi==0.99.1
uvicorn
requests
pydantic==1.10.12

上記のテキストはクリエイティブ・コモンズ 表示-継承ライセンスのもとで利用できます。

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