This article explains how to restructure a FastAPI project by moving the main file into an “app” directory for better code organization.
In this lesson, we will adjust the project structure to improve code organization by moving the main file into a dedicated folder named “app”. This change groups all application-specific code in one place and simplifies package management.
Below is an example of a FastAPI endpoint for updating a post. Notice that this code sample is presented only once for clarity:
Copy
Ask AI
@app.put("/posts/{id}")def update_post(id: int, post: Post): index = find_index_post(id) if index is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Post with id: {id} does not exist" ) post_dict = post.dict() post_dict['id'] = id my_posts[index] = post_dict return {"data": post_dict}
We are now creating a new folder named app to store our main application file. In Python, a folder can be used as a package if it contains an __init__.py file.
Even though the __init__.py file can be empty, its presence is essential as it signals to Python that the folder should be treated as a package.
After creating the app folder and adding an __init__.py file inside it, move the main file into the app directory. At this point, you’ll encounter an error because the startup command is still referencing the main file from the base directory.
In this command, main referred to the file in the project’s base directory. Now that the main file has been moved into the app package, the startup command must be updated to indicate the new package location:
This updated command directs Uvicorn to search for the file named main within the app folder and then use the FastAPI instance (named app) defined therein.
After starting the application with the updated command, you might see output similar to the following:
Copy
Ask AI
(venv) C:\Users\sanje\Documents\Courses\fastapi>uvicorn app.main:app --reloadINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO: Started reloader process [21236] using watchgodINFO: Started server process [4760]INFO: Waiting for application startup.INFO: Application startup complete.127.0.0.1:50834 - "GET /posts/1 HTTP/1.1" 200 OK