djangoのRESTAPIを作成する
https://zenn.dev/whitecat_22/articles/f826daf43155cd
https://cloudsmith.co.jp/blog/backend/2023/08/2462017.html
-
devcontainerで開く
-
.env.org
をコピーして.env
に書き換える -
マイグレーションファイルを生成
$ python manage.py makemigrations bread
-
マイグレーションを実行し,テーブルを作成する
$ python manage.py migrate
-
管理ユーザーを作成する。
(ユーザー名,メールアドレス,パスワードを設定。)
$ python manage.py createsuperuser
-
開発サーバーを起動
$ python manage.py runserver
-
以下のurlにアクセス。
http://localhost:8000/admin/
Product>追加と進み,テーブルに適当な要素を追加してみる。 たとえば,
Name: あんぱん, Price:120, Description": "あんこたっぷり", "review": "Good"
など。 -
APIでデータベースにアクセスしてみる。
-
GET
curl -X GET http://localhost:8000/bread/bread/ # 以下のようにレスポンスが返る。"priceWithTax"が計算され,テーブルに追記されているのがポイント。 # [{"name":"あんぱん","price":120,"description":"あんこたっぷり","review":"Good","priceWithTax":132}]
-
POST
curl -X POST -H "Content-Type: application/json" -d '{"name": "しょくぱん", "price": 150, "description": "もちもち", "review": "Soso"}' http://localhost:8000/bread/bread/
-
DELETE
curl -X DELETE http://localhost:8000/bread/bread/1/
-