# FAST API 實作
## Python + VScode
## Set up the environment
1. Install **Python**
2. Install **VSCode**
3. Set up virtual environment -- **venv** (Advantages: This will not influence other projects!)
* Type `py -3 -m venv <name>` in the terminal
* The project will run the python.exe under **/venv/Scripts**
* Type `venv\Scripts\activate.bat` in the terminal
* Type `pip install fastapi` in the terminal
* The packages will exist in the **lib** folder
4. Run all the code under the virtual environment
* Install Code Runner -> Run the code with `Ctrl + Alt + N`
## FastAPI
The original route I established !!
```python==
from fastapi import FastAPI
app = FastAPI()
@app.get("/") #get() is method
def get_user(): #Function_name should be Descriptive as possible
return {"message": "Hello World"} #Normally transfer data by json format universally
```
Type `uvicorn main:app` in the terminal to execute the code
Type `uvicorn main:app --reload` in the terminal can reload the page automatically
Install **Postman**
```python=
@app.post("/createposts")
# Extract all the fields in th body and convert into Python dictionary, then store it to payLoad
def create_posts(payLoad: dict = Body(...)):
print(payLoad)
return {"new post": f"title{payLoad['title']} content: {payLoad['content']}"}
```
## Why we need Schema?
Since back-end doesn't want **arbitrary** data from the front-end, we need to force the client to send data in a schema that we expect.
Import **pydantic package** to define the schema `from pydantic import BaseModel`
Link: https://pydantic-docs.helpmanual.io/
```python=
class Post(BaseModel):
title: str
content: str
```
```python=
@app.post("/createposts")
def create_posts(new_post: Post): # Validate for us!
print(new_post.title)
return {"data": "new post"}
```
Based on the above two code, the pydantic package will help us **validate** whether the schema is correct or not.
If not, 