install fastapi using following commend
pip install fastapi[all]
Create a project directory named it then start
Step #1: Create a server directory and add an** init.py **file to it. Then, create the following subdirectories within the server directory:
- DB: This directory will contain all the code for database connections.
- Models: This directory will house the models for all tables.
- Routers: This directory will contain all the routers. Ensure that each table has a separate router.
- Schemas: This directory will contain all the Pydantic schemas for each table. Ensure that each table has a separate file for its schema.
- Utils: This directory will contain utility functions and code. Note: all of the above directory needs file name init.py check this picture to understand file structure
step#2
create backend.py inside server directory and it should contain following code and adjust it according to your needs
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from server.routers import test_question_router
app = FastAPI(title="Backend for Tip for fastapi", version="0.0.1",docs_url='/')
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=True,
)
app.include_router(your_router.router)
@app.get("/ping")
def health_check():
"""Health check."""
return {"message": "Hello I am working!"}
Step#3
then Create file name
run.py out side the server directory
add following code
import os
import uvicorn
ENV: str = os.getenv("ENV", "dev").lower()
if __name__ == "__main__":
uvicorn.run(
"server.backend:app",
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", 8080)),
workers=int(os.getenv("WORKERS", 4)),
reload=ENV == "dev",
)
Now you can run you FastAPI project with just following commend
python run.py
this is my github
https://github.com/MuhammadNizamani
this is my squad on daily.dev
https://dly.to/DDuCCix3b4p
check code example on this repo and please give a start to my repo
https://github.com/MuhammadNizamani/Fastapidevto
Top comments (0)