---
# System prepended metadata

title: FastAPI Note
tags: [fastapi, python]

---

# FastAPI usage note
### Installation
```shell
$pip install fastapi
$pip install "uvicorn[standard]"
```
# Simplest Example

- create a main.py
```python=
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
```
run main.py with following commod
```shell
$uvicorn main:app --reload
```

- main.py can also be  create like this
```python=
from fastapi import FastAPI
import uvicorn

app = FastAPI()

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

if __name__ == '__main__':
    uvicorn.run("main:app", port=8000,reload=True)
```

run main.py with following commod
```shell
$python main.py
```
## Running Screen
```conda
INFO:     Will watch for changes in these directories: ['/fastAPI']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [53822] using WatchFiles
INFO:     Started server process [53827]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```
## Web Screen 
Open your browser and enter the following URL: http://127.0.0.1:8000/ 
You will see a webpage with this appearance

![截圖 2023-11-16 15.43.38 #center](https://hackmd.io/_uploads/rydNOBX4p.png)
---
## Interactive API docs
FastAPI will auto create the api Document at http://127.0.0.1:8000/
![截圖 2023-11-16 15.51.10](https://hackmd.io/_uploads/HJ3g9SQ4T.png)


# running on specifying host and port 
```shell
$uvicorn main:app --host 0.0.0.0 --port 80 
```
or in main.py
```python=
if __name__ == '__main__':
    uvicorn.run("main:app", host='0.0.0.0', port=8000,reload=True)
```
```shell
$python main.py
```
# GET Request
```python=
@app.get("/get_number/{number}") 
async def read_number(number: int):
    return {"number": number}
```
## Send get request
![截圖 2023-11-16 16.48.01](https://hackmd.io/_uploads/rkCrwLQNT.png)
## Return Value
![截圖 2023-11-16 16.48.26](https://hackmd.io/_uploads/ryLvv8Q4p.png)


# POST Request
### Installation
```
$pip install pydantic
```
## create data model from BaseModel
```python=
from fastapi import FastAPI
from pydantic import BaseModel

# create data model
class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

@app.post("/items/")
async def create_item(item: Item):
    return item
```
## Send get request
![截圖 2023-11-16 16.53.04](https://hackmd.io/_uploads/B1RuO8QET.png)

## Return Value
![截圖 2023-11-16 16.53.23](https://hackmd.io/_uploads/SJlqOUXEa.png)
