Creating Your First Web API with FastAPI
Following our introduction to Introduction to RESTful APIs: Principles and Design, this article will guide you through Creating Your First Web API with FastAPI. FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints.
📚 Prerequisites
- Python 3.6+ installed.
- Basic understanding of Python and type hints.
- Understanding of RESTful principles.
🎯 Article Outline: What You'll Master
- ✅ Installation: How to install FastAPI and an ASGI server.
- ✅ Core Implementation: Creating a basic FastAPI application.
- ✅ Running the Server: How to run your FastAPI application.
- ✅ Interactive API Docs: Exploring the automatic interactive documentation.
🧠 Section 1: The Core Concepts of FastAPI
FastAPI is built on two main pillars:
- Starlette: A lightweight ASGI (Asynchronous Server Gateway Interface) framework/toolkit.
- Pydantic: A data validation and settings management library using Python type hints.
This combination allows FastAPI to be incredibly fast and easy to use, with features like automatic data validation, serialization, and documentation.
💻 Section 2: Deep Dive - Implementation and Walkthrough
Let's create our first "Hello, World" API.
2.1 - Installation
First, install FastAPI and an ASGI server, such as Uvicorn.
pip install fastapi uvicorn
2.2 - Creating the Application
Create a file named main.py:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Step-by-Step Code Breakdown:
from fastapi import FastAPI: We import theFastAPIclass.app = FastAPI(): We create an instance of theFastAPIclass.@app.get("/"): This is a path operation decorator. It tells FastAPI that the function below is responsible for handling requests that go to the path/using agetoperation.@app.get("/items/{item_id}"): This path has a path parameteritem_id.item_id: int: This is a type hint. FastAPI uses it to validate the path parameter.q: str | None = None: This is a query parameter. It's optional and will have a default value ofNone.
🛠️ Section 3: Running the Server
To run the application, use Uvicorn:
uvicorn main:app --reload
main: the filemain.py(the Python "module").app: the object created inside ofmain.pywith the lineapp = FastAPI().--reload: make the server restart after code changes. Only use for development.
Now, open your browser at http://127.0.0.1:8000. You should see {"Hello":"World"}.
🔬 Section 4: Interactive API Docs
FastAPI automatically generates interactive API documentation for your application.
- Swagger UI: Go to
http://127.0.0.1:8000/docs. You'll see an interactive UI where you can test your API endpoints directly from the browser. - ReDoc: Go to
http://127.0.0.1:8000/redoc. You'll see an alternative documentation format.
This is one of FastAPI's most powerful features, as it makes developing and testing APIs incredibly efficient.
💡 Conclusion & Key Takeaways
You have created your first web API with FastAPI, run it, and explored the automatic documentation.
Let's summarize the key takeaways:
- FastAPI is a modern, high-performance web framework for Python.
- It uses type hints for data validation and documentation.
- It provides automatic interactive API docs.
➡️ Next Steps
In the next article, "API Routing and HTTP Verbs for RESTful Endpoints", we will explore how to create more complex routes and use different HTTP methods.
Glossary
- FastAPI: A modern web framework for building APIs with Python.
- ASGI: Asynchronous Server Gateway Interface. The successor to WSGI for asynchronous Python web servers.
- Uvicorn: An ASGI server.
- Pydantic: A data validation library.