DEV Community

Cover image for Getting Started with FastAPI: A Beginner’s Guide Using Python 🐍
wizcoderx
wizcoderx

Posted on

Getting Started with FastAPI: A Beginner’s Guide Using Python 🐍

Introduction to FastAPI

Imagine you're at a restaurant. You tell the waiter your order, and the waiter communicates it to the kitchen and brings back your food. FastAPI works just like that waiter. It is a modern, high-performance web framework for building APIs with Python, letting your app/application talk to other apps/applications efficiently.

Official FastAPI Docs

So, why FastAPI instead of Flask or Django REST?

Because FastAPI is as fast as Node.js and Go, uses Python type hints for validation, generates automatic docs, and is asynchronous by design. Compared to Flask, it's more scalable out of the box. Unlike Django REST Framework, it's minimal and lightning fast.

In the real world, FastAPI is used in production by companies building GenAI backends, microservices, ML model deployment, and startups that need to move fast with clean code and performance in mind.

Implementation

To follow along, make sure Python is installed on your system. You can download it from python.org.

We'll use a virtual environment (venv) to isolate dependencies — this helps avoid breaking your global packages and keeps the project clean.

Next, we'll use PyCharm IDE Community Edition, because the community edition is free :) — it offers smart code suggestions, automatic virtual environment detection, and built-in terminal, making Python development smooth and efficient. You can download it from PyCharm Download and search for PyCharm Community Edition.

Now, let's build your first FastAPI app:

  1. Create a folder named fastapi_intro
  2. Open PyCharm and create a new Python project inside that folder. OR right-click on the folder and click "open with PyCharm", this will create a main.py file automatically.
  3. Open the terminal inside PyCharm which is mostly at the bottom left of the screen and run:
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode
  1. Create a file named main.py if it doesn't exist
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI"}
Enter fullscreen mode Exit fullscreen mode
  1. Run it using the below command in terminal:
uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode
  1. Open your browser and go to http://127.0.0.1:8000/docs — FastAPI auto-generates interactive Swagger docs! 🎉

A Quick Note on BaseModel

Before we jump into the mini project, let's understand this line:

from pydantic import BaseModel
Enter fullscreen mode Exit fullscreen mode

FastAPI uses Pydantic for data validation. BaseModel lets you define the structure of the data your API expects. When a request is made, FastAPI uses that model to:

  • Validate the input (e.g., check if it's an int)
  • Parse and document it automatically in the Swagger UI

Think of it as a Python class that ensures your API only accepts clean, structured data — no manual checks needed!

Think of BaseModel like a blueprint for incoming data — it tells FastAPI exactly what shape the data should be. Just like a form with required fields, it checks the input and throws an error if something's missing or incorrect.

Mini Project: Simple Calculator API

Let's build a mini calculator with two FastAPI endpoints — one for addition and one for subtraction.

Step-by-step:

NOTE: Installing the correct version of Pydantic is important, so before proceeding with the following step, kindly install Pydantic version 2.

Run the following in your terminal (inside your virtual environment):

pip uninstall pydantic
pip install "pydantic<2.0.0"
Enter fullscreen mode Exit fullscreen mode
  1. Update your main.py:
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Numbers(BaseModel):
    number_1: int
    number_2: int

@app.post("/add")
def add(numbers: Numbers):
    result = numbers.number_1 + numbers.number_2
    return {
        "number_1": numbers.number_1,
        "number_2": numbers.number_2,
        "result": str(result)
    }

@app.post("/subtract")
def subtract(numbers: Numbers):
    result = numbers.number_1 - numbers.number_2
    return {
        "number_1": numbers.number_1,
        "number_2": numbers.number_2,
        "result": str(result)
    }
Enter fullscreen mode Exit fullscreen mode
  1. Run the server again:
uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode
  1. Test both endpoints at http://127.0.0.1:8000/docs using the Swagger UI.

Your input JSON:

{
  "number_1": 10,
  "number_2": 5
}
Enter fullscreen mode Exit fullscreen mode

Expected output:

{
  "number_1": 10,
  "number_2": 5,
  "result": "15"
}
Enter fullscreen mode Exit fullscreen mode

If you want an in-depth understanding of the above code, then please read the below; otherwise, jump to the Challenge section.

In-Depth Analysis of Code:

1. In-depth Explanation (What the Code Does)

This code creates a simple API with FastAPI that exposes two endpoints: one to add and one to subtract two numbers. The FastAPI() class sets up the web app. Then, using BaseModel from Pydantic, a class Numbers is defined which describes the shape of the input data — expecting two integers. When a POST request is made to either /add or /subtract, FastAPI automatically parses the JSON input based on Numbers, validates that number_1 and number_2 are both integers with the help of BaseModel, and injects the validated data into the corresponding function (add or subtract). The function then performs the calculation and returns a JSON response containing the input values and the result as a string. FastAPI also auto-generates interactive docs based on this setup using Swagger.

2. Analogy (Line-by-Line Intuition)

Think of building a tiny calculator counter inside a digital restaurant.

  • from fastapi import FastAPI: This is like setting up the front desk where people come in with requests.
  • from pydantic import BaseModel: This brings in the clipboard where we write down what kind of form customers must fill out.
  • app = FastAPI(): You're now opening the restaurant and saying "we're ready to take orders!"
  • class Numbers(BaseModel): ...: This is the form customers must fill, saying: "Please give me two whole numbers to work with."
  • @app.post("/add"): You're putting up a sign at a counter saying "For addition, hand your form here."
  • def add(numbers: Numbers):: The chef (your function) picks up the form and sees the numbers written.
  • result = numbers.number_1 + numbers.number_2: The chef does the math using the values from the form.
  • return {...}: The waiter hands back a neat receipt showing the input numbers and the final total.

Same goes for the /subtract counter — it's just a different chef doing subtraction instead of addition.

Challenge:

Now it's your turn!

Create two more endpoints:

  • /multiply
  • /divide

Try writing them yourself — and post your versions in the comments section! 💬

What's Next?

In the next chapter, we will see how we can use FastAPI with GenAI apps like Gemini API to ask questions and get responses back from it.

Stay tuned. It's wizcoderx!

Top comments (0)