5
0

Fast APIでJavascriptからのPOST通信を試す。

Last updated at Posted at 2023-12-22

NS高所属の @tester_ringo です。
たまにpythonで何かしらを書く程度の者です。

私はwebに関してほとんど知識がありませんが、最近私の中でwebの需要が高まっていました。
けれど何から勉強を行えばいいのかわからず、ひとまず何か作ろうと思いたちました。
その過程で行ったPOST通信の備忘録です。初心者向けです。
しかし、明確に説明できるほどの知識がないため解説はありません。
よって初心者向けでもないです。(ターゲット不明。

何かしらの手助けとなれれば幸いです。

目的

Fast APIでpythonとjavascriptからPOST通信を行う事。
詳細などは調べればすぐに出てくるため、手順のみ。

環境

  • python 3.11.2
  • javascript
  • windows

0. 準備

pipを用いて各種ライブラリのインストール

  • Fast API
  • uvicorn
  • pydantic
  • requests
pip install fastapi uvicorn pydantic requests

1. 起動

ファイル構成

fast_api/
└main.py

簡易的なサーバファイルの作成。
Fast APIと調べると真っ先に出てくる。

main.py
from fastapi import FastAPI

app = FastAPI()

# get
@app.get("/")
async def root():
    return {"return" : "message"}

ターミナルから起動。(カレントディレクトリへの移動を忘れずに

uvicorn main:app --reload

2. POST通信(pythonから)

サーバファイルにpostメソッドの処理の追加。
後々のために一度CORSを無効化する。(1敗

main.py
import random
from fastapi import FastAPI
from pydantic import BaseModel

class Name(BaseModel):
    name: str

app = FastAPI()

# 後のためのCORS回避
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# get
@app.get("/")
async def root():
    return {"response" : "message"}

# psot
@app.post("/")
async def new_naming(req: Name):
    name = req.name
    new_name = name.upper()[random.randint(0, len(name)-1)]
    return {"response": f"油屋の長によるとあなたの名前は今日から「{new_name}」らしい。"}

お試し通信フ用ァイルを用意し、実行。

req.py
import requests
import json

url = "http://127.0.0.1:8000/" #localhost
data = {"name" : "山田太郎"}

response = requests.post(url, json.dumps(data))
print(response.json())

実行結果

$ python req.py
{'response': '油屋の長によるとあなたの名前は今日から「山」らしい。'}

3. POST通信(javascriptから)

簡単にjsからもpostを試してみる。(ブラウザ使用。
非同期処理によりjs初めての人には多少ややこしくなっている。(私
詳しく知りたい場合は非同期処理やpromiseなどを検索すると良い。
(ちなみにheaderのcontent typeを知らず1敗

req用エセ.html
<h1 id="result">result</h1>
<script>
async function test_post(url, name) {
    const response = await fetch(url, {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
            "name": name
        })
    });
    const result = await response.json();
    return result["response"];
};

test_post("http://127.0.0.1:8000/", "山田太郎").then((result) => { //レスポンス後の処理.
    const label = document.getElementById("result");
    label.textContent = result;
});
</script>

ブラウザの表示結果
山田太郎さんの新しい名前.png

終わり。

5
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
5
0