Getting Started with FastAPI: A Beginner's Guide
Guilherme Bueno Rodrigues
Tech Lead na SKF Group | Python | AWS | Terraform
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It's designed to be easy to use and learn, making it a great choice for beginners. In this article, we'll walk you through the basics of getting started with FastAPI, including installation, creating your first API, and some practical use cases.
First of all, what is an API?
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. Think of it as a bridge that enables two applications to talk to each other and share data or functionality. APIs are used in various contexts, such as web development, mobile apps, and cloud services. They allow developers to access certain features or data of an application without needing to understand its internal workings.
For example, when you use a weather app on your phone, it likely communicates with a weather service's API to fetch the latest weather data and display it to you.
There are several popular frameworks for building APIs in Python. Here are some of the most common ones:
Each of these frameworks has its own strengths and use cases, so the best choice depends on your specific needs and preferences.
Why FastAPI?
Before we dive in, let's briefly discuss why FastAPI is a good choice:
Prerequisites
To follow along with this guide, you should have:
Step 1: Install Python
First, ensure you have Python 3.7 or higher installed on your machine. You can download the latest version of Python from the official website.
Step 2: Create a project directory
You can use the command below or create a folder manually. If you do that manually, open the folder in your code editor
mkdir my_first_api
cd my_first_api
Step 3: Installation
First, you'll need to install FastAPI and an ASGI server called uvicorn to run your application. Open your terminal and run the following command:
pip install fastapi uvicorn
Step 3: Creating Your First FastAPI Application
Let's create a simple FastAPI application. Inside your project directory (step 2) create a new file called main.py and add the following code:
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):
return {"item_id": item_id, "q": q}
Here's a breakdown of what this code does:
领英推荐
Step 4: Running Your Application
To run your FastAPI application, use the following command in your terminal:
uvicorn main:app --reload
Open your browser and navigate to https://127.0.0.1:8000. You should see the JSON response {"Hello": "World"}. ??
Step 5: Interactive API Documentation
One of the coolest features of FastAPI is its automatically generated interactive API documentation. You can access it by navigating to `https://127.0.0.1:8000/docs` for Swagger UI or `https://127.0.0.1:8000/redoc` for ReDoc.
Use Cases
Here are a few practical use cases for FastAPI:
Some more examples
Example 1: Path Parameters
Path parameters allow you to capture values from the URL. Here's an example of how to use them:
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
In this example, the user_id is captured from the URL and returned in the response.
Example 2: Query Parameters
Query parameters are optional parameters that can be added to the URL. Here's how to use them:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
In this example, skip and limit are query parameters with default values. You can access this endpoint with URLs like https://127.0.0.1:8000/items/?skip=5&limit=20.
Example 3: Request Body
You can also send data in the body of a request. FastAPI makes it easy to handle JSON data:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/")
def create_item(item: Item):
return item
In this example, we define an Item model using Pydantic. The create_item endpoint accepts an Item object in the request body and returns it.
Conclusion
FastAPI is a powerful and easy-to-use framework for building APIs with Python. With its speed, ease of use, and excellent documentation, it's a great choice for beginners and experienced developers alike. By following this guide, you should now have a basic understanding of how to create and run a FastAPI application. Happy coding!