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
main.py
: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
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:
This endpoint allows clients to send JSON payloads like:
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
Post a Comment