-
Create directory
json-api
and placemain.py
anddata.json
in it. -
Create a Python environment and install the packages
fastapi
and"uvicorn[standard]"
:
$ python3 -m virtualenv venv
$ source venv/bin/activate
$ pip install fastapi
$ pip install "uvicorn[standard]"
To save this packages list into requirements.txt
, do pip freeze > requirements.txt
. Afterwards, you can simply install the packages in requirements.txt
in a new environment as follows:
$ pip install -r requirements.txt
- Run the code:
$ uvicorn main:app --reload
INFO: Will watch for changes in these directories: ['/home/luis/json-api']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [22187] using watchgod
INFO: Started server process [22189]
INFO: Waiting for application startup.
INFO: Application startup complete.
- HTTP requests:
GET /recipes
$ curl -X 'GET' \
'http://127.0.0.1:8000/recipes' \
-H 'accept: application/json'
{"recipeNames":["scrambledEggs","garlicPasta","butteredBagel","chai"]}
GET /recipes/details/{recipe_name}
$ curl -X 'GET' \
'http://127.0.0.1:8000/recipes/details/garlicPasta' \
-H 'accept: application/json'
{"details":{"ingredients":["500mL water","100g spaghetti","25mL olive oil","4 cloves garlic","Salt"],"numSteps":5}}
POST /recipes
$ curl -X 'POST' \
'http://127.0.0.1:8000/recipes/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name" : "butteredBagel",
"ingredients" : ["1 bagel", "butter"],
"instructions" : ["cut the bagel", "spread butter on bagel"]
}'
{"detail":"Recipe already exists"}
PUT /recipes
$ curl -X 'PUT' \
'http://127.0.0.1:8000/recipes/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name" : "butteredBagel",
"ingredients" : ["1 bagel", "2 tbsp butter"],
"instructions" : ["cut the bagel", "spread butter on bagel"]
}'