- Create virtual environment for FastAPI
#create virtual environment
python -m venv ./venv
#activate virtual environment (Windows)
.\venv\Scripts\activate
#activate virtual environment (Linux/Mac)
source venv/bin/activate
-
Install libraries : fastapi, ASGI (Asynchronous Server Gateway Interface) server(in this case we will use Uvicorn), SQLAlchemy and psycopg2 to connect to postgres databases. You can type pip install requirements.txt for install all libraries.
-
Install postman for run API after run FastAPI apps. You can download here
Lets define project structure bellow :
+-- app
| +-- __init__.py
| +-- crud.py
| +-- config.py
| +-- main.py
| +-- models.py
| +-- routes.py
| +-- schemas.py
+-- venv
- Type command bellow. It will run apps with default ip 127.0.0.1 and port 8000
cd app
uvicorn main:app --reload
- Open Postman, type url http://127.0.0.1:8000 and methode GET then save as Home. Click Send button then will display output "Hallo"
- Next define other request as bellow :
-
Request Name : Create New. URL : http://127.0.0.1:8000/book/create. Method : POST. Body: Choose raw and type
{ "parameter": { "title": "Apache Spark for Data Scientist", "description": "Book about Apache Spark for Data Scientist" } }
save as Create New. Click Send button then will display Response 200 OK
-
Request Name : Get All. URL : http://127.0.0.1:8000/book/. Method : GET. Save as Get All then click Send button will display output bellow
-
Request Name : Get By Id. URL : http://127.0.0.1:8000/book/{id}(id with get from run request Get All). Method : GET. Save as Get By Id then click Send button will display output bellow
-
Request Name : Update. URL : http://127.0.0.1:8000/book/update. Method : PATCH . Body: Choose raw and type
{ "parameter": { "id": "3", "title": "Apache Spark for Data Scientist", "description": "Book about Apache Spark for Data Scientist for Beginner" } }
save as Update. Click Send button then will display output bellow
-
Request Name : Delete. URL : http://127.0.0.1:8000/book/{id}(id with get from run request Get All). Method : DELETE. Save as Delete then click Send button will display output bellow
-