Host Your Fastapi server on Heroku for Free...
Ajo Alex
Posted on December 30, 2021
Create a Fastapi project
for that install some pip packages
pip install fastapi
and you need a ASGI server for production
here we use uvicorn
pip install uvicron
and you need an another package named gunicorn
pip install gunicorn
write some code
Here we have to create a file for our python code. so create a file named main.py
and write some code like this
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
Run the code
uvicorn main:app --reload
this will run your app in localhost and the default port will be 8000. Here main
is the filename and app
is the fastapi object.
Next is adding some stuffs for hosting.
Create requirements.txt
for creating the file just run:
pip freeze > requirements.txt
it will create the file and contents like be this
anyio==3.4.0
asgiref==3.4.1
certifi==2021.10.8
charset-normalizer==2.0.9
click==8.0.3
fastapi==0.70.1
gunicorn==20.1.0
h11==0.12.0
idna==3.3
pydantic==1.8.2
requests==2.26.0
sniffio==1.2.0
starlette==0.16.0
typing-extensions==4.0.1
urllib3==1.26.7
uvicorn==0.16.0
Its the list of packages need to run your app.
Create Procfile
create a file named Procfile
without any extensions and paste the below code
web: gunicorn -w 3 -k uvicorn.workers.UvicornWorker main:app
this contain the running script for execute your app
here main is the python file name and app is the fastapi object. so it can be changed..
Now the app is ready for deploy.
Create a Github Repo and push the code to it
and create a new heroku app linked with the respective github repo in heroku dashboard.
After bulid finished in heroku just go to your-app-url/docs
for get your api documentation
Posted on December 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024