Build A Simple FastAPI App On GitHub
Build a Simple FastAPI App on GitHub
What’s up, code enthusiasts! Today, we’re diving deep into building a simple FastAPI app and getting it up on GitHub . You know, those projects that are super easy to get started with but still pack a punch? Yeah, those. Whether you’re a seasoned dev or just dipping your toes into the world of web frameworks, this guide is for you. We’ll break down how to set up your FastAPI project, write some basic API endpoints, and then push it all to your GitHub repository. It’s all about making things accessible and reproducible, so you can easily share your work or use it as a foundation for something bigger. We’re talking about streamlining your workflow, guys, making it as smooth as butter.
Table of Contents
FastAPI is this awesome, modern web framework for building APIs with Python. It’s super fast (hence the name!), easy to learn, and comes with built-in data validation using Python type hints. This means fewer bugs and more time for you to actually build cool stuff. And when you combine it with GitHub, the world’s leading platform for software development, you get a powerful combo for version control, collaboration, and showcasing your projects. Think of it as your digital garage where you can build, tinker, and share your creations with the world. So, grab your favorite IDE, a cup of coffee, and let’s get this party started!
Setting Up Your FastAPI Project: The Foundation
Alright, let’s get down to business. The first step in creating your
simple FastAPI app
is to set up your project environment. This involves a few key things: creating a project directory, setting up a virtual environment, and installing FastAPI and a server like Uvicorn. Don’t sweat it; it’s more straightforward than you think! We’re going to make this as painless as possible. First off, create a new folder for your project. You can name it anything you like, but let’s go with
my_fastapi_app
for now. Open your terminal or command prompt and run:
mkdir my_fastapi_app
cd my_fastapi_app
Next up, we need a virtual environment. This is super important, guys, because it keeps your project’s dependencies isolated from other Python projects on your system. It’s like having a separate toolbox for each project. To create a virtual environment, you can use Python’s built-in
venv
module. Run the following command:
python -m venv venv
This will create a
venv
folder inside your project directory. Now, you need to activate this virtual environment. The command differs slightly depending on your operating system. On Windows, it’s:
.\venv\Scripts\activate
And on macOS or Linux:
source venv/bin/activate
You’ll see
(venv)
at the beginning of your terminal prompt, which means your virtual environment is active. Awesome! Now that our environment is ready, it’s time to install FastAPI and Uvicorn. Uvicorn is an ASGI server that runs FastAPI applications. You can install them both using pip:
pip install fastapi uvicorn[standard]
The
[standard]
part installs some extra goodies for Uvicorn that make it even better. With these installed, you’ve successfully set up the foundation for your
simple FastAPI app
! It’s all about these foundational steps, and once they’re done, the rest just flows. High-five yourself, you’ve already made great progress!
Writing Your First FastAPI Endpoint: The Core Logic
Now for the fun part – writing some code! Let’s create a basic API endpoint for our
simple FastAPI app
. This endpoint will do something super simple, like returning a greeting message. Create a new Python file in your project directory, named
main.py
. This is where all our API logic will live.
Open
main.py
in your favorite text editor and let’s write some Python. First, we need to import FastAPI:
from fastapi import FastAPI
Next, we need to create an instance of the FastAPI class. This instance will be the main point of interaction for our API:
app = FastAPI()
Now, let’s define our first endpoint. We’ll create a GET request endpoint at the root URL (
/
). This endpoint will return a JSON response.
@app.get("/")
def read_root():
return {"message": "Hello, World! This is my simple FastAPI app."}
Let’s break this down. The
@app.get("/")
is a decorator. It tells FastAPI that the function immediately following it (
read_root
) should handle GET requests made to the root path (
/
). When someone sends a GET request to this path, the
read_root
function will be executed. The function simply returns a Python dictionary, and FastAPI automatically converts this dictionary into a JSON response. Easy peasy, right?
To test this out, save your
main.py
file. Go back to your terminal (make sure your virtual environment is still active) and run Uvicorn:
uvicorn main:app --reload
Here,
main
refers to the
main.py
file (the module), and
app
refers to the
FastAPI()
instance we created inside
main.py
. The
--reload
flag is super handy because it makes the server restart automatically whenever you make changes to your code. You should see output indicating that Uvicorn is running, something like:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Now, open your web browser and go to
http://127.0.0.1:8000
. You should see the JSON response:
{"message": "Hello, World! This is my simple FastAPI app."}
. How cool is that? You’ve just created and run your very first
simple FastAPI app
endpoint! We can also visit
http://127.0.0.1:8000/docs
to see the automatically generated interactive API documentation (Swagger UI). This is one of the many amazing features of FastAPI that makes development a breeze.
Adding More Functionality: Parameters and Paths
Okay, so a root endpoint is cool, but APIs are usually about more than just a static greeting. Let’s make our simple FastAPI app a bit more dynamic by introducing path parameters and query parameters. This is where the real power of APIs starts to shine!
First, let’s add an endpoint that takes a parameter directly in the URL path. For example, let’s create an endpoint that greets a specific user by name. We’ll modify our
main.py
file. Add the following code below your
read_root
function:
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Let’s unpack this. The path is now
"/items/{item_id}"
. The
{item_id}
part is a
path parameter
. FastAPI automatically detects this and expects a value to be passed in the URL. We’ve also defined a function parameter
item_id: int
. The
: int
here is a Python type hint. FastAPI uses these type hints for
data validation
. So, if someone tries to access
/items/hello
instead of
/items/5
, FastAPI will automatically return a validation error, which is super neat!
We’ve also added another parameter,
q: str | None = None
. This is a
query parameter
. Query parameters come after the
?
in a URL, like
/items/5?q=somequery
. The
| None = None
signifies that this parameter is optional. If it’s not provided, it will be
None
. This allows for more flexible API calls.
Save
main.py
and reload your server (if you’re using
--reload
, it should have already restarted). Now you can test this endpoint in a few ways:
-
Go to
http://127.0.0.1:8000/items/5. You should get:{"item_id": 5, "q": null} -
Go to
http://127.0.0.1:8000/items/10?q=testquery. You should get:{"item_id": 10, "q": "testquery"} -
Try going to
http://127.0.0.1:8000/items/abc. You’ll get a validation error becauseabcis not an integer, thanks to FastAPI’s type hinting!
See? Building a simple FastAPI app gets more powerful with just a few lines of code. You can define various types of parameters, specify default values, and let FastAPI handle the validation. This really speeds up development and reduces the chances of silly errors creeping into your application. We’re building robust APIs here, guys, without breaking a sweat!
Preparing for GitHub: Version Control Basics
So far, we’ve built a simple FastAPI app and tested it locally. Now, it’s time to get it onto GitHub . This is crucial for version control, collaboration, and basically having a backup of your awesome code. If you don’t have a GitHub account yet, head over to GitHub.com and sign up – it’s free!
First, we need to initialize a Git repository in our project folder. Git is the version control system that GitHub uses. If you don’t have Git installed, you’ll need to download and install it from
git-scm.com
. Once Git is installed, open your terminal in the
my_fastapi_app
directory (make sure your virtual environment is deactivated for this step, or just be mindful of your commands):
git init
This command creates a hidden
.git
directory in your project, which is where Git stores all the version history. Now, we need to tell Git which files to track. It’s a good practice to use a
.gitignore
file to specify files and directories that Git should ignore, like your virtual environment folder (
venv
) and any compiled Python files (
*.pyc
). Create a file named
.gitignore
in the root of your project directory and add the following lines:
venv/
__pycache__/
*.pyc
.DS_Store
Now, let’s add all the files we want to track to the staging area. This is the first step before making a commit:
git add .
The
.
means add all files in the current directory. Then, we commit these staged files. A commit is like a snapshot of your project at a specific point in time. It’s essential to write a clear commit message:
git commit -m "Initial commit: Setup simple FastAPI app"
This command saves the changes with a descriptive message. You’ve now made your first commit! This is the foundation of version control. Every time you make significant changes, you’ll want to
git add .
and
git commit -m "Your descriptive message"
. This creates a history that you can go back to if needed.
Pushing Your App to GitHub: Sharing Your Work
With our local Git repository set up and our initial commit made, the next logical step is to push our simple FastAPI app to GitHub . This makes your code accessible from anywhere and allows others to see it, collaborate, or even contribute. It’s the grand unveiling!
First, go to your GitHub account and create a new repository. Click the
+
sign in the top-right corner and select “New repository”. Give your repository a name (e.g.,
my-fastapi-app
), optionally add a description, and choose whether it should be public or private. For this guide, let’s assume you’re making it public.
Do not initialize the repository with a README, .gitignore, or license file
, as we’ve already done this locally.
After creating the repository on GitHub, you’ll see a page with instructions. You’ll need the URL of your new repository. It will look something like
https://github.com/your-username/my-fastapi-app.git
.
Now, back in your terminal, still in your
my_fastapi_app
directory, you need to link your local repository to the remote GitHub repository. This is done using the
git remote add
command:
git remote add origin https://github.com/your-username/my-fastapi-app.git
Replace
https://github.com/your-username/my-fastapi-app.git
with the actual URL of your GitHub repository. The
origin
is a conventional name for the remote repository.
Now, to push your local commits to GitHub, use the
git push
command:
git push -u origin main
If your default branch is named
master
instead of
main
, use
git push -u origin master
.
This command uploads your committed changes to the
main
branch of your
origin
(GitHub) repository. The
-u
flag sets the upstream branch, so in the future, you can simply use
git push
.
If this is your first time pushing from this machine, Git might ask for your GitHub username and password, or it might prompt you to use a Personal Access Token (PAT) if you have two-factor authentication enabled. Follow the on-screen instructions. Once it’s done, refresh your GitHub repository page, and you should see all your project files, including
main.py
and
.gitignore
!
Congratulations! You’ve successfully created a simple FastAPI app , managed it with Git, and pushed it to GitHub . This is a huge milestone. You now have a version-controlled, shareable project that you can build upon. Keep coding, keep pushing, and keep building awesome things, guys!