FastAPI Project Setup With GitHub: A Quick Guide
Hey guys! Let's dive into setting up a FastAPI project with GitHub. This guide will walk you through the essentials, from creating a new project to setting up a repository, writing your first API endpoint, and pushing your code to GitHub. Whether you're a seasoned developer or just starting, this tutorial will provide a solid foundation for building and managing your FastAPI projects using Git.
Initializing Your FastAPI Project
First off, you're going to want to set up the basics for your FastAPI project. This involves creating a new directory, initializing a Python virtual environment, and installing FastAPI along with its dependencies. Let's get started by opening your terminal and navigating to the folder where you want to create your project. You can use the mkdir command to create a new directory and cd to enter it. For example:
mkdir my-fastapi-project
cd my-fastapi-project
Next, you'll need to create a virtual environment. Virtual environments help you manage dependencies for each project in isolation. This prevents conflicts between different projects that might require different versions of the same libraries. To create a virtual environment, you can use venv (or virtualenv if you're using an older version of Python). Here’s how:
python3 -m venv venv
Once the virtual environment is created, you need to activate it. Activating the environment modifies your shell's PATH so that the Python interpreter and scripts installed in the virtual environment are used. Here’s how to activate it:
source venv/bin/activate # On Linux and macOS
.\venv\Scripts\activate # On Windows
After activating the virtual environment, you'll see the environment name (usually venv) in parentheses at the beginning of your terminal prompt. Now, you can install FastAPI and Uvicorn, an ASGI server, which you’ll use to run your application. FastAPI is the star of the show, and Uvicorn helps to serve your API.
pip install fastapi uvicorn
With FastAPI and Uvicorn installed, you’re ready to create your first FastAPI application file. Create a file named main.py (or any name you prefer) and open it in your favorite text editor or IDE. This file will contain your API endpoints and application logic. The initial setup is crucial for keeping your project organized and manageable, which will save you headaches down the road.
Setting Up Your First API Endpoint
Alright, let's get into the fun part: coding your first API endpoint! Open the main.py file you created and add the following code. This simple example creates a basic FastAPI application with a single endpoint that returns a greeting.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
In this code snippet, you first import the FastAPI class from the fastapi library. Then, you create an instance of the FastAPI class, which is the core of your application. The @app.get("/") decorator tells FastAPI that the read_root function should handle GET requests to the root path ("/"). This is how FastAPI knows which function to call when a user accesses the root URL of your API.
The read_root function is an asynchronous function (defined with async def), which is a recommended practice in FastAPI for handling requests efficiently. This function simply returns a Python dictionary, which FastAPI automatically converts into a JSON response. In this case, it returns {"Hello": "World"}, so when a user visits the root URL, they will see this JSON response.
To run your FastAPI application, you'll use Uvicorn. Open your terminal, navigate to the directory containing your main.py file, and run the following command:
uvicorn main:app --reload
Here’s what this command does:
uvicorn: This is the command-line tool to run the Uvicorn server.main:app: This tells Uvicorn to import theappobject from themain.pyfile. Theappobject is the FastAPI instance you created.--reload: This option enables automatic reloading of the server whenever you make changes to your code. This is super useful during development because you don't have to manually restart the server every time you modify your code. The--reloadoption is great for development but should not be used in a production environment.
After running the command, you should see output indicating that the server has started. By default, Uvicorn runs the application on http://127.0.0.1:8000. Open this URL in your web browser, and you should see the {"Hello": "World"} JSON response. Congrats, you've created your first API endpoint with FastAPI!
Setting Up a GitHub Repository
Now that you have a basic FastAPI application, it’s time to set up a GitHub repository to store your code. If you don't already have a GitHub account, you'll need to create one. Once you have an account, follow these steps to create a new repository:
- Go to GitHub: Navigate to the GitHub website and log in.
- Create a New Repository: Click the "+" button in the upper-right corner and select "New repository."
- Repository Details:
- Repository Name: Enter a name for your repository (e.g.,
my-fastapi-project). - Description: Add a brief description of your project (optional).
- Public/Private: Choose whether you want the repository to be public or private. Public repositories are visible to everyone, while private repositories are only accessible to you and collaborators you specify.
- Initialize with a README: Check this box to automatically create a
README.mdfile in your repository. A README file is a good place to provide information about your project. - Add .gitignore: Select "Python" from the dropdown menu. This will create a
.gitignorefile that tells Git which files and directories to ignore (e.g., virtual environment files, temporary files). - Choose a License: Select a license for your project (optional). Common licenses include MIT, Apache 2.0, and GPL 3.0.
- Repository Name: Enter a name for your repository (e.g.,
- Create Repository: Click the "Create repository" button to create your new repository.
After creating the repository, GitHub will provide instructions on how to connect your local project to the remote repository. These instructions will involve using Git commands in your terminal. Here’s a breakdown of the steps:
-
Initialize Git: If you haven't already, initialize Git in your project directory. This creates a
.gitsubdirectory that stores the repository metadata.
git init ```
-
Add Remote Repository: Add the URL of your remote repository to your local Git configuration. Replace
<repository_url>with the URL of your GitHub repository.
git remote add origin <repository_url> ```
-
Commit Changes: Add your project files to the staging area and commit them with a descriptive message.
git add . git commit -m "Initial commit" ```
-
Push to GitHub: Push your local commits to the remote repository on GitHub. This uploads your code to GitHub.
git push -u origin main ```
Writing a Proper .gitignore File
A .gitignore file specifies intentionally untracked files that Git should ignore. This is crucial for keeping your repository clean and avoiding committing unnecessary files, such as virtual environment directories, temporary files, and sensitive information. Create a .gitignore file in the root of your project and add the following entries:
# Byte-compiled / optimized / DLL files
__pycache__/
*.pyc
*.pyo
*.pyd
*.so
*.dll
# Distribution / packaging
.eggs/
dist/
build/
# IDE-specific files
.idea/
.vscode/
*.swp
# OS generated files
.DS_Store
Thumbs.db
# Virtual environment
virtualenv/
venv/
myvenv/
*/venv/
.venv/
# Sensitive information (if any)
*.env
secrets.json
Each line in the .gitignore file specifies a pattern that Git should ignore. You can use wildcards (*) to match multiple files or directories. Here’s a breakdown of some common entries:
__pycache__/: Ignores Python bytecode cache directories.*.pyc: Ignores compiled Python files.venv/: Ignores the virtual environment directory.*.env: Ignores environment files that may contain sensitive information.
By using a .gitignore file, you can ensure that your repository only contains the necessary source code and project files, making it easier to collaborate with others and manage your project.
Best Practices for GitHub Management
To effectively manage your FastAPI project on GitHub, consider the following best practices:
-
Use Branches: Use branches for developing new features or fixing bugs. Create a new branch for each feature or bug fix, and merge it back into the main branch when it’s complete. This helps to keep your main branch stable and makes it easier to manage changes.
git checkout -b feature/new-feature ```
-
Write Clear Commit Messages: Write clear and descriptive commit messages. A good commit message should explain what changes were made and why. This makes it easier to understand the history of your project and to revert changes if necessary.
git commit -m "Add new feature: Implement user authentication" ```
-
Use Pull Requests: Use pull requests for code review. When you’re ready to merge a branch into the main branch, create a pull request. This allows other developers to review your code and provide feedback before it’s merged. This helps to catch bugs and improve the quality of your code.
-
Regularly Update Your Repository: Regularly update your local repository with changes from the remote repository. This ensures that you have the latest version of the code and that you’re not working with outdated code.
git pull origin main ```
-
Keep Your Dependencies Up to Date: Keep your project dependencies up to date. Regularly check for updates to your dependencies and update them as needed. This helps to ensure that your project is secure and that you’re using the latest features and bug fixes.
pip install --upgrade fastapi uvicorn ```
By following these best practices, you can effectively manage your FastAPI project on GitHub and collaborate with other developers more efficiently.
Conclusion
Setting up a FastAPI project with GitHub is a straightforward process that involves initializing your project, creating API endpoints, setting up a GitHub repository, and following best practices for repository management. By following the steps outlined in this guide, you can create a solid foundation for building and managing your FastAPI projects using Git. Remember to write clear commit messages, use branches for development, and regularly update your repository to ensure that you have the latest version of the code. Happy coding, and good luck with your FastAPI projects!