DEV Community

Cover image for My Journey into FastAPI
TyronOdame
TyronOdame

Posted on

My Journey into FastAPI

Introduction

In the world of full-stack development, there are lots of different languages and frameworks to choose from. Each framework comes with its own unique set of rules and functionalities that can either make your life easier or harder, depending on your task.

Today, I will be talking about FastAPI, and I'll be going over all of the necessary information that you will need to succeed when trying to implement this web framework.

Why FastAPI

You're probably thinking to yourself, you should even bother with learning FastAPI. The real question is, why haven't you learned it sooner? FastAPI stands out as an excellent backend framework. It provides high performance and speed. FastAPI is so fast that it rivals Node.js and Go among Python frameworks. This speed and high performance come from its asynchronous capabilities.

Oh yeah, let's not forget about the fact that the framework significantly reduces development time through its intuitive design. In other words, creating APIs with this bad boy here will be a breeze. With its built-in API documentation, it eliminates the need for separate documentation maintenance.

Think of FastAPI like a smart kitchen. In an old-school kitchen, you would most likely need to check if ingredients are fresh, keep track of cooking times with separate timers, and most annoying of all, constantly have to monitor multiple dishes. At this rate, you'll spend more time preparing to cook and cleaning up than you would actually cooking. In a smart kitchen, you have built-in sensors that can check for rotten foods, a Siri-type AI that can read out steps to the recipe, and to top it all off, multiple induction cooktops can cook different dishes simultaneously without interference. This allows you to actually focus on cooking rather than dividing your attention to other things like the annoyance of prepping.

Now that I've got your attention, let's jump right into how you can start using FastAPI today.

Getting Started

Let's dive right into it. First, you want to set up your IDE so that it supports Python (Python is what FastAPI is coded in). I will be using Visual Studio Code as my IDE.

Installation
Before we start coding, you'll need to install FastAPI and a server:


pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

(Insert image here)

Once you have successfully downloaded Python and configured it into your IDE, we can dive into the syntax breakdown.

Basic Syntax

This will primarily be going over the implementation of FastAPI. I will not be going deep into the fundamentals of Python. To fully benefit from this blog post, I would recommend that you have a strong foundation in the basics of Python before you continue...

Now that that's out of the way, let's hop right in.


from fastapi import FastAPI

api = FastAPI()

@api.get("/")
def read_root():
    return {'Message': 'Hello World'}
Enter fullscreen mode Exit fullscreen mode

The code snippet that you see above is a basic endpoint that returns the message 'Hello World' once "/" is visited. Let's break down why this is happening:


from fastapi import FastAPI
Enter fullscreen mode Exit fullscreen mode

This is the heart of the file. Without this line of code, we would not be able to use FastAPI. Before you start coding ANYTHING, make sure that you are importing FastAPI from the fastapi package.


api = FastAPI()
Enter fullscreen mode Exit fullscreen mode

This sets the invocation of FastAPI to api, making it super easy to call it throughout the file. Without this line of code, there is no FastAPI. This allows for all the features to be available for use.


@api.get("/")
Enter fullscreen mode Exit fullscreen mode

This line of code is the endpoint declaration. This is how the frontend knows what to do at a certain endpoint, though more precisely, it tells the FastAPI server what function to execute when a GET request is made to this path.


def read_root():
    return {'Message': 'Hello World'}
Enter fullscreen mode Exit fullscreen mode

Last but certainly not least, this is the function that will run once the FastAPI server receives the request on the specific endpoint.

Put them all together, and you'll have yourself a working FastAPI backend file. The more complex the project, the more code you'll need.

To run your server, use:


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

Now let's step it up a notch and get into path parameters.

Path Params

To keep this short and simple, a path parameter is a parameter that gets input from the user as part of the URL. When the user makes a request to the URL, the path param value gets pulled and passed to the matching endpoint's function.

Okay, maybe not as simple as pitched, let's look at some code:


# Sample data for demonstration
all_todos = [
    {'todo_id': 1, 'task': 'Learn FastAPI'},
    {'todo_id': 2, 'task': 'Build an API'}
]

@api.get("/todos/{todo_id}")
def get_todo(todo_id: int):
    for todo in all_todos:
        if todo['todo_id'] == todo_id:
            return {'result': todo}
    return {'error': 'Todo not found'}
Enter fullscreen mode Exit fullscreen mode

The code above should not look too foreign to you; it's the same format as last time but with some new puzzle pieces. Let's go over them:


@api.get("/todos/{todo_id}")
Enter fullscreen mode Exit fullscreen mode

Same as before, this line is the endpoint that FastAPI server is waiting to receive from the frontend to run a specific function. However, it looks like we will be putting some dynamic info in the mix 🤔.


def get_todo(todo_id: int):
    for todo in all_todos:
        if todo['todo_id'] == todo_id:
            return {'result': todo}
Enter fullscreen mode Exit fullscreen mode

This is the same as the other function declaration, except this function takes in a parameter named 'todo_id'.

Look familiar? That's because it's the same variable name as the endpoint declaration. This is what allows the user's input from the URL to be passed into the function. When an HTTP request comes from the frontend with a parameter in the URL path, FastAPI extracts the value and passes it to the function parameter.

Conclusion

I hope this has given you a good foundation into starting the journey into FastAPI. With this, you have everything you need to get into topics like Query Params and the final boss... Pydantic.

Look out for that 🤫

Thanks for your time and help! I appreciate it!

Best,

Tyron

Top comments (0)