Skip to main content

FastAPI: How to Start with One Simple Project




FastAPI has rapidly gained popularity in the Python community, and for good reason. Designed to be fast, easy to use, and robust, it enables developers to build APIs quickly while maintaining code readability and performance.

If you’re new to FastAPI, this guide walks you through setting up your first simple project from scratch. By the end, you’ll have a working REST API and the foundational knowledge to grow it into something more powerful.



Why FastAPI?


Before we dive into code, it’s worth understanding what sets FastAPI apart:

  • Speed: As the name suggests, it's fast—both in development time and performance, thanks to asynchronous support.

  • Automatic docs: With Swagger UI and ReDoc automatically generated from your code.

  • Type hints: Built on Python type annotations, improving editor support and catching errors early.

  • Built on Starlette and Pydantic: Ensures high performance and robust data validation.


Prerequisites

You’ll need:

  • Python 3.7+

  • Basic knowledge of Python

  • Familiarity with HTTP concepts (GET, POST, etc.)

Let’s get started.



Step 1: Project Setup

First, create a new directory for your project

mkdir fastapi-simple-api

cd fastapi-simple-api


Create a virtual environment and activate it:

python -m venv venv

source venv/bin/activate  # On Windows: venv\Scripts\activate


Install FastAPI and a production server (Uvicorn):

pip install fastapi uvicorn




Step 2: Create the App

Create a file called main.py:

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}


This minimal app has:

  • A root endpoint (/) that returns a greeting.

  • A dynamic endpoint (/items/{item_id}) that accepts a path parameter and an optional query parameter.


Step 3: Run the Server

Start your API using Uvicorn:

uvicorn main:app --reload


The --reload flag restarts the server upon code changes, ideal for development.

Now visit:

  • http://127.0.0.1:8000/ — see your API in action.

  • http://127.0.0.1:8000/docs — access the Swagger UI.

  • http://127.0.0.1:8000/redoc — see the ReDoc UI.



Step 4: Add a POST Endpoint


Extend your app to accept POST data:


from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.post("/items/")
def create_item(item: Item):
    return {"received_item": item}


This endpoint allows clients to send JSON payloads like:


{
  "name": "Book",
  "price": 29.99,
  "is_offer": true
}


FastAPI automatically validates and parses this data into a Python object.


Step 5: Next Steps


Now that your project is running, here are some suggestions to expand it:

  • Add PUT and DELETE methods

  • Connect to a database (e.g., SQLite with SQLAlchemy)

  • Organize code using routers and dependencies

  • Add authentication (OAuth2, JWT)



Final Thoughts

FastAPI strikes a perfect balance between power and simplicity. In just a few lines, you get a fully functioning API with validation, documentation, and high performance out of the box.

Starting with a simple project like this not only teaches you the fundamentals but sets the stage for building scalable web applications and microservices.

Happy coding! 

Comments

Popular posts from this blog

Vicharaks Axon Board: An Indian Alternative to the Raspberry Pi

  Vicharaks Axon Board: An Alternative to the Raspberry Pi Introduction: The Vicharaks Axon Board is a versatile and powerful single-board computer designed to offer an alternative to the popular Raspberry Pi. Whether you're a hobbyist, developer, or educator, the Axon Board provides a robust platform for a wide range of applications. Key Features: High Performance: Equipped with a powerful processor (e.g., ARM Cortex-A72). High-speed memory (e.g., 4GB or 8GB LPDDR4 RAM). Connectivity: Multiple USB ports for peripherals. HDMI output for high-definition video. Ethernet and Wi-Fi for network connectivity. Bluetooth support for wireless communication. Storage: Support for microSD cards for easy storage expansion. Optional onboard eMMC storage for faster read/write speeds. Expandable: GPIO pins for custom projects and expansions. Compatibility with various sensors, cameras, and modules. Operating System: Compatible with popular Linux distributions (e.g., Ubuntu, Debian). Support for o...

An Introduction to Quantitative Finance: Unlocking the Power of Data and Mathematics in Financial Markets

  Introduction Quantitative finance is a field that merges mathematical models, statistical analysis, and computational techniques to analyse financial markets. In today’s data-driven world, the reliance on quantitative methods has revolutionised trading, risk management, and investment strategies. But what exactly is quantitative finance, and why is it so important? In this blog, we’ll explore the fundamentals of quantitative finance, its applications, and the tools used by "quants." 1. What is Quantitative Finance? Quantitative finance involves using mathematical models and algorithms to understand financial markets and make informed decisions. Unlike traditional finance, which may rely heavily on qualitative analysis and expert judgment, quantitative finance uses data, statistics, and computer algorithms to forecast market trends, price assets, and manage risks. Historical Roots : The origins of quantitative finance can be traced back to the 1950s with the development of t...

Understanding the Differences Between PATCH and PUT in HTTP Methods

  In the world of web development, understanding the various HTTP methods is crucial for building efficient and scalable applications. Two commonly used HTTP methods for updating resources are PATCH and PUT. While they might seem similar at first glance, they serve different purposes and are used in distinct scenarios. In this blog post, we'll explore the differences between PATCH and PUT, and when to use each method. What is PUT? The PUT method is used to update a resource on the server. When you use PUT, you send a complete representation of the resource you want to update. This means that the data you send should include all the fields of the resource, not just the ones you want to change. Characteristics of PUT: Idempotent: No matter how many times you apply a PUT request, the state of the resource will remain the same. Repeated PUT requests with the same data will not change the resource after the first successful request. Complete Update: PUT updates the entire resource. If...