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...

Mastering Error Handling in Programming: Best Practices and Techniques

 In the world of software development, errors are inevitable. Whether you're a novice coder or a seasoned developer, you will encounter errors and exceptions. How you handle these errors can significantly impact the robustness, reliability, and user experience of your applications. This blog post will explore the importance of error handling, common techniques, and best practices to ensure your software can gracefully handle unexpected situations. Why Error Handling is Crucial Enhancing User Experience : Well-handled errors prevent applications from crashing and provide meaningful feedback to users, ensuring a smoother experience. Maintaining Data Integrity : Proper error handling ensures that data remains consistent and accurate, even when something goes wrong. Facilitating Debugging : Clear and concise error messages help developers quickly identify and fix issues. Improving Security : Handling errors can prevent potential vulnerabilities that malicious users might exploit. Commo...