DEV Community

Cover image for Create FastAPI App Like pro part-1
Muhammad Ishaque Nizamani
Muhammad Ishaque Nizamani

Posted on • Updated on

Create FastAPI App Like pro part-1

install fastapi using following commend

pip install fastapi[all]
Enter fullscreen mode Exit fullscreen mode

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:

  1. DB: This directory will contain all the code for database connections.
  2. Models: This directory will house the models for all tables.
  3. Routers: This directory will contain all the routers. Ensure that each table has a separate router.
  4. Schemas: This directory will contain all the Pydantic schemas for each table. Ensure that each table has a separate file for its schema.
  5. 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

Image description

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!"}

Enter fullscreen mode Exit fullscreen mode

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",
    )


Enter fullscreen mode Exit fullscreen mode

Now you can run you FastAPI project with just following commend

python run.py
Enter fullscreen mode Exit fullscreen mode

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)