In this post I will be explaining/showing how you can install python fastapi on your device.
Before installing fastapi, you eed to install python 3.7+. If you want to check weather pytohon is installed on your windows/mac/linux, you can use the following command,
For mac => python3 --version
For linux/windows => python3 --version,
If you haven't installed python, you can find the installation process here .
Now its time to install fastapi!
To install fastapi, you can use the following command => pip install "fastapi[all]"
This will install all the required material to run fastapi.
If you want to install it part by part. you can remove the [all] in the above command and you have to install uvicorn to run the server.
If you did not use the "all" flag while installing fastapi you need to install uvicorn to run the server.
To install uvicorn, you can use the following command => pip install "uvicorn[standard]"
After installing fastapi and and its dependencies, you need to create a "main.py"(you can use any name here).
In the main.py file write the folllowing code:
from fastapi import FastAPI #importing fastapi
app = FastAPI() # create an instance of fastapi
@app.get("/") #decorator
async def root(): #root function
return {"message": "Hello this is my first get request"}
Code explanation:
- First We import FastAPI from fastapi library,
- Then we create an instance of fastapi and assign it to a variable name "app"
- then we ctreate a decorator
- then we call create a function below the decorator to handel the get methos and send data/ the logic part. in this function we just return an object.
Run the server
To run the server, you can use the following command,
command = uvicorn main:app --reload
Command explanation:
- "main": the file name we wrote the code on,
- "app": the fastapi instance we created in the main.py file,
- "--reload": automatically reload the server whenever we make a new change and save it.
In the output you will see the url where the server is running.
More in-dept guide on installing and setting up fastapi by creating virtual machine on your system can be found here.
Comments
Post a Comment