DEV Community

Cover image for FastAPI Todo App: Setting Up Your Todo App Project
James
James

Posted on

FastAPI Todo App: Setting Up Your Todo App Project

Getting Started with FastAPI: Setting Up Your Todo App Project

I. Introduction

In this blog series, readers will learn how to build a To-Do App with FastAPI. The series will guide you step by step in creating a To-Do application from scratch using FastAPI, a modern and high-performance Python web framework. The content covers everything from setting up the development environment to deploying the app. By the end of the series, readers will have created their own To-Do App and gained a solid grasp of FastAPI.

Each post in the series will focus on a specific aspect of the development process, providing clear explanations and practical code examples. The goal is to equip readers with the knowledge and skills needed to build web applications using FastAPI. Whether you're a beginner looking to learn web development or an experienced developer exploring FastAPI, this series aims to provide valuable insights and hands-on experience.

The initial post will introduce FastAPI to help you set up your development environment and create your FastAPI application.

Blog Code in Todo_Part1 dir: GitHub - jamesbmour/blog_tutorials

II. Introduction to FastAPI and its benefits

A. What is FastAPI?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It's designed to be easy to use, fast to code, ready for production, and based on the latest Python features.

B. Key features of FastAPI

  1. Fast performance: FastAPI is built on top of Starlette for the web parts and Pydantic for the data parts, making it one of the fastest Python frameworks available.
  2. Easy to use and learn: FastAPI is very developer-friendly, with its intuitive design and excellent documentation.
  3. Automatic API documentation: FastAPI automatically generates interactive API documentation (using Swagger UI and ReDoc) based on your code.
  4. Type checking and editor support: FastAPI leverages Python's type hints, providing excellent editor support with autocompletion and error detection.

C. Comparison with other Python web frameworks

Compared to other popular Python web frameworks like Flask or Django, FastAPI offers:

  • Better performance
  • Built-in API documentation
  • Easier handling of request/response validation
  • Native asynchronous support

D. Why FastAPI is suitable for building a Todo App

For our Todo App, FastAPI is an excellent choice because:

  • It allows rapid development of our API endpoints.
  • It provides automatic request validation, reducing the amount of code we need to write.
  • The built-in API documentation will make testing our endpoints easy.
  • Its high performance will ensure our app remains responsive even as it grows.

III. Setting up the development environment

A. Installing Python (3.7+)

Make sure you have Python 3.7 or later installed. You can download it from python.org.

B. Creating a virtual environment

It's best practice to use a virtual environment for Python projects. Here's how to create one:

  1. Using venv:
python -m venv todo-env
source todo-env/bin/activate  # On Windows, use `todo-env\Scripts\activate`
Enter fullscreen mode Exit fullscreen mode
  1. Using conda (alternative):
conda create --name todo-env python=3.9
conda activate todo-env
Enter fullscreen mode Exit fullscreen mode
  1. Install Poetry
poetry install  
# activate the virtual environment  
poetry shell  
Enter fullscreen mode Exit fullscreen mode

C. Installing FastAPI and its dependencies

Now, let's install FastAPI and Uvicorn (an ASGI server):

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

IV. Creating a basic FastAPI application

A. Writing the first FastAPI script

Create a new file named main.py and add the following code:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello, FastAPI!"}
Enter fullscreen mode Exit fullscreen mode

B. Explanation of the code structure

  • We import FastAPI from the fastapi module.
  • We create an instance of FastAPI called app.
  • We define a route using the @app.get("/") decorator, which tells FastAPI that the function below handles GET requests to the root URL ("/").
  • The async def root(): function is our route handler, which returns a JSON object.

C. Running the FastAPI application using Uvicorn

To run the application, use the following command:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

This command tells Uvicorn to:

  • Look for an app object in main.py
  • Run it as an ASGI application
  • Watch for file changes and reload the server (--reload option)

D. Accessing the automatic API documentation (Swagger UI)

Once your server is running, you can access the automatic API documentation by navigating to http://127.0.0.1:8000/docs in your web browser.

V. Defining the project structure

A. Creating a new directory for the Todo App

Create a new directory for your project:

mkdir fastapi-todo-app
cd fastapi-todo-app
Enter fullscreen mode Exit fullscreen mode

B. Setting up a basic project structure

Create the following files in your project directory:

  1. main.py (entry point)
  2. requirements.txt
  3. .gitignore

C. Explaining the purpose of each file and directory

  • main.py: This is the main entry point of our application where we define our FastAPI app and routes.
  • requirements.txt: This file lists all the Python packages required for our project.
  • .gitignore: This file specifies which files and directories should be ignored by Git version control.

Add the following to your requirements.txt:

fastapi
uvicorn
Enter fullscreen mode Exit fullscreen mode

And add this to your .gitignore:

__pycache__
*.pyc
todo-env/
Enter fullscreen mode Exit fullscreen mode

VI. Implementing a simple "Hello, World!" endpoint

A. Creating a root endpoint

We've already created a root endpoint in our main.py. Let's modify it slightly:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Welcome to the Todo App!"}
Enter fullscreen mode Exit fullscreen mode

B. Returning a JSON response

FastAPI automatically converts the dictionary we return into a JSON response.

C. Testing the endpoint using a web browser

Run your server with uvicorn main:app --reload, then navigate to http://127.0.0.1:8000 in your web browser. You should see the JSON response.

D. Using the interactive API documentation

Navigate to http://127.0.0.1:8000/docs to see the Swagger UI documentation for your API. You can test your endpoint directly from this interface.

VII. Next steps

In the upcoming blog post, we will explore FastAPI in more detail by developing the fundamental features of our Todo App. We will establish endpoints for adding, retrieving, updating, and deleting todos. As an exercise, you can add a new endpoint that provides the current date and time when accessed.

@app.get("/current-time")  
async def get_current_time():  
    current_time = datetime.now()  
    return {  
        "current_date": current_time.strftime("%Y-%m-%d"),  
        "current_time": current_time.strftime("%H:%M:%S"),  
        "timezone": current_time.astimezone().tzname()  
    }
Enter fullscreen mode Exit fullscreen mode

VIII. Conclusion

Congratulations! You've successfully set up your development environment, created your first FastAPI application, and learned about the basic structure of a FastAPI project.

We've covered a lot of ground in this post. We've discussed what FastAPI is and why it's a great choice for our Todo App. We've also written our first endpoint and run our application.

In the next post, we'll start building the core functionality of our Todo App. Stay tuned, and happy coding!

If you would like to support me or buy me a beer feel free to join my Patreon jamesbmour

Top comments (1)