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?

学習記録10/9

Posted at

本日の目的・ゴール

目的

CRUDの基礎をつかむためにほかのAPIやライブラリは除いて学習
https://youtu.be/m_4PpxsMtVU?si=a2gmSngkM9gKAkAr

YOUTUBEに乗っていたコードを参考にswaggerで実行CRUDの登録や更新、削除の感覚をつかむ

ゴール
CRUDを理解すること

学んだこと

1 毎日学んだコードを記録するために新しいフォルダとファイルの作成をコマンドで作成した。今後はコードを消さずにすべて記録する

mkdir week1
mkdir week2
main.pyとclient.pyを作成したweek1フォルダに移動
mv main.py client.py week1
week2内に新しいファイルmain2.pyとclient.pyを作成
New-Item week2/main2.py
New-Item week2/client2.py
Main2.py
from fastapi import FastAPI
# fastAPIクラスをインポート

app = FastAPI()


@app.get("/")
# デコレータ リクエストメゾットがGETでURLがドメインまでのリクエストが来た時に呼び出される
def read_root():
    return {"message":"サブAPIです"}   

@app.post("/items/")
def create_item(name:str, price: float):
    return item

@app.put("/items/{item_id}")
def update_item(item_id: int , name: str, price: float):
    return {"name": name, "price": price}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    return {"message": f"Item {item_id} deleted successfully"}

POST
image.png

PUT
image.png
DELETE
image.png

躓いたこと

1 今日は新しく作成したmain2.pyでコードを実行したが、ファイル名が変更になったため今まで使っていたサーバーを起動するコマンドが使えなかった。
このコマンドを使えばサーバー起動できるものと何も考えず使用していたため、
構造を理解するのに役立った。

week2内に新しいファイルmain2.pyとclient2.pyを作成
uvicorn week2.main2:app --reload
uvicorn <ファイル名>:<変数名> --reload

2 研修中ではLinuxを利用してコマンドを打っていたため、ファイル作成といえばtouchだったが、ターミナルの種類によって使うコマンドが異なることを学んだ。

week2 の中に main2.py と client2.py を作成
New-Item week2/main2.py
New-Item week2/client2.py

3 POSTリクエストを /docs 上で実行したときに「500 Internal Server Error」が発生した。

Main2.py
@app.post("/items/")
def create_item(name: str, price: float):
    return item

itemが定義されていないというただの打ち間違えによるエラーだったが、エラーを知られていく中で「リクエストボディ」という概念を知った。

以下chatgptより引用

💡 FastAPIでサーバーにデータを送る3つの方法
FastAPIでは、クライアント(ブラウザや他のプログラム)からサーバーにデータを送るとき、主に3つの方法があります。

方法 名称 使い方 主な用途
① URLの中 パスパラメータ /items/{id} /items/3 特定のデータを指定する(例:3番のアイテム)
② URLの後ろ クエリパラメータ /items/?name=nana&price=2000 /items/?name=nana&price=2000 検索・条件指定・簡単な値の受け渡し
③ リクエストの本文(Body) リクエストボディ JSON形式で本文に送る { "name": "nana", "price": 2000 } データ登録・更新などで複数データをまとめて送る
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?