I will follow Fast API's official document tutorials to learn fastly Python and Fast API itself.
Let's begin with set up Fast API project.
STEP1. Install Fast API.
Run the below codes on terminal.
pip install "fastapi[all]"
- 'pip' is a package manager for tons of Python dependencies.
- 'all' in the middle of square brackets means including all of optional dependencies and features when install Fast API project.
If you meet error message "command not found: pip", please check below.
- Did you install Python?
- If you installed Python above 3.4, 'pip' would be installed too.
- If not above 3.4, install it individually.
- If you run on mac os, you could need to upgrade 'pip'. Because mac os already had Python2 which cause the error nof found 'pip' something, you should upgrade pip command with pip3 (if you installed Python3). So, you need the code below.
pip3 install --upgrade pip
STEP2. Write and run main app
Firstly, make a folder for Python project and write a file which name sholud be a 'main' and extenstion is 'py'.
In 'main.py' file, write below code.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
And run below on terminal.
uvicorn main:app --reload
What does this command means?
- unvicorn: is a ASGI(Asychronous Server Gateway Interface) web server implement for Python.
- - I'm going to post about unvicorn more later.
- main:app: is 'a python module name':'attribute of the module(an created object in main.py.)'.
- --reload: only for development, reload the server after the code is changed.
Then, go to http://127.0.0.1:8000 and check {"message":"Hello World"} on your brower.
STEP3. Understand the codes meaning one by one.
1. Import FastAPI class.
from fastapi import FastAPI
2. Create FastAPI instance.
app = FastAPI()
3. Define a path operation decorater.
- @+something is a decorator notation.
- a decorator takes a function right below and does somethine with it.
- In this code, when receiving reguests from a path '/' get opreration, a function right below this decorator would do something.
@app.get("/")
4. Define a function for a path operation decorater.
- 'async' is for asychronous function. so it doesn't need in this codes.
async def root():
return {"message": "Hello World"}