18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FastAPIで作ったアプリを無料で使えるDetaにデプロイして簡単にWebAPIを公開する

Last updated at Posted at 2022-06-28

Detaのメジャーアップデートにより以下の手順のままではできないかもしれません。

 最近、FastAPIを少し勉強したので、Deta上にWebAPIを公開してみます。メッチャ簡単にできます。

FastAPIとは

 FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。

 主な特徴:

 高速: NodeJS や Go 並みのとても高いパフォーマンス(Starlette と Pydantic のおかげです)。 最も高速な Python フレームワークの一つです。
 高速なコーディング: 開発速度を約 200%~300%向上させます。
 少ないバグ: 開発者起因のヒューマンエラーを約 40%削減します。
 直感的: 素晴らしいエディタのサポートや オートコンプリート。 デバッグ時間を削減します。
 簡単: 簡単に利用、習得できるようにデザインされています。ドキュメントを読む時間を削減します。
 短い: コードの重複を最小限にしています。各パラメータからの複数の機能。少ないバグ。
 堅牢性: 自動対話ドキュメントを使用して、本番環境で使用できるコードを取得します。Standards-based: API のオープンスタンダードに基づいており、完全に互換性があります。

FastAPIの公式ドキュメントより引用

 こちらの記事でもFastAPIが急速に人気を伸ばしているとありますね。

Detaとは

 Herokuのような無料で使えるクラウドサービスで、クレカ登録も必要ないので安心して使うことができます。Detaには現在、以下の3つのサービスがあります。

Deta Base:機能豊富なAPIを備えたすぐに使用できるNoSQLデータベース。
Deta Micros:スケーラブルなNode.jsおよびPythonアプリを数秒でデプロイします。
Deta Drive:画像とファイルをアップロード、ホスト、提供します。

 こちらが公式HPですがまだ英語表記のみとなっています。

 ちなみに、この記事ではBaseとMicrosを使用してWebAPIを作成します。

Detaアカウント登録

 [Deta公式HP]にアクセスし「Join Deta」ボタンを押して、ユーザーネーム、パスワード、メールアドレスを登録して確認メールの「Verify Email」を押して認証をすればアカウント登録完了です。

Detaインストール

 Deta CLIのインストール(Windows、PowerShellで実行)

iwr https://get.deta.dev/cli.ps1 -useb | iex

 Mac、Linuxはこちらを参考にしてインストールしてください。

 パッケージのインストール

pip install deta

ソースコード

 このソースコードはFlaskで書かれているDetaの公式HPのPythonチュートリアルの内容をFastAPIに書き換えて作成しました。

main.py
from deta import Deta
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel

deta = Deta("c0922pnk_********************************")
db = deta.Base('simpleDB')

app = FastAPI()

class User(BaseModel):
    name: str
    age: int
    hometown: str


@app.get("/")
def index():
    return {"message": "Hello world"}


@app.post("/users", status_code=201)
def create_user(user: User):
    user = db.put(user.dict())
    return user


@app.get("/users/<key>")
def read_user(key: str):
    user = db.get(key)
    return user if user else JSONResponse({"erorr": "Not found"}, 404)



@app.put("/users/<key>")
def update_user(key: str, user: User):
    if db.get(key):
        user = db.put(user.dict(), key)
        return user
    else:
        return JSONResponse({"erorr": "Not found"}, 404)


@app.delete("/users/<key>")
def delete_user(key: str):
    if db.get(key):
        db.delete(key)
        return JSONResponse({"message": "deleted"}, 200)
    else:
        return JSONResponse({"erorr": "Not found"}, 404)
requirements.txt
fastapi

 このmain.pyとrequirements.txtを同じディレクトリに入れておきます。

デプロイ

 ターミナルで上記2つのファイルのあるディレクトリに移動し、以下を実行。

Detaにログイン

deta login

Detaにデプロイ

deta new

デプロイに成功すると以下のようなメッセージが返ってきます。

Successfully created a new micro
{
        "name": "********",
        "id": "************************************",
        "project": "********",
        "runtime": "python3.9",
        "endpoint": "https://******.deta.dev",
        "region": "ap-southeast-1",
        "visor": "disabled",
        "http_auth": "disabled"
}

https://******.deta.devがエンドポイントになります。

https://******.deta.devにアクセスするとmain.pyの17~19行目で書かれている処理の"message": "Hello world"が表示されていることがわかります。

qiita_2022_0628_1.jpg

またhttps://******.deta.dev/docsにアクセスするとFastAPIの自動ドキュメント生成機能によって作られたSwagger UIでAPI仕様の確認やテストができます。

qiita_2022_0628_2.jpg

最後に

 以上のように簡単にWebAPIを無料でデプロイできました。Detaはまだまだ知名度が低いですが、使いやすいので個人的に今後も使っていこうと思います。

18
17
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
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?