Building a Python REST API with FastAPI for Real-Time Data Processing
Learn how to create a beginner-friendly REST API using FastAPI in Python to process real-time data efficiently and effectively.
FastAPI is a modern, fast web framework for building APIs with Python 3.7+ based on standard Python type hints. It’s perfect for developing RESTful APIs that require high performance and real-time data processing. In this tutorial, we will build a simple Python REST API using FastAPI that accepts real-time data, processes it, and returns results quickly.
### Step 1: Install FastAPI and Uvicorn First, you need to install FastAPI and Uvicorn, an ASGI server used to serve your app. Run the following command in your terminal:
pip install fastapi uvicorn### Step 2: Create Your FastAPI Application Create a new Python file, for example, `main.py`. This will be the entry point for your API.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Define a data model for incoming real-time data
class DataPoint(BaseModel):
sensor_id: int
value: float
timestamp: float
@app.post("/process/")
async def process_data(data: DataPoint):
"""Process incoming real-time data and return a response"""
# Example processing: simple threshold check
threshold = 50.0
alert = data.value > threshold
return {
"sensor_id": data.sensor_id,
"alert": alert,
"processed_value": data.value * 1.1, # example of transformation
"timestamp": data.timestamp
}### Step 3: Run Your API Use Uvicorn to run your FastAPI application by running this command in the terminal:
uvicorn main:app --reloadThe `--reload` flag restarts the server whenever you make code changes, which is great during development. Your API should now be running locally at `http://127.0.0.1:8000`.
### Step 4: Test Your API You can test your API using tools like `curl` or Postman. Here’s an example using `curl` to send a POST request with JSON data:
curl -X POST "http://127.0.0.1:8000/process/" -H "Content-Type: application/json" -d '{"sensor_id":1, "value":55.5, "timestamp":1686800000.0}'You should receive a JSON response indicating whether the sensor value exceeds the threshold and the processed value.
### Summary In this beginner-friendly tutorial, you built a simple REST API using FastAPI that accepts real-time sensor data, performs basic processing, and returns a response. FastAPI makes it very easy to define data models and endpoints with automatic documentation and validation. As you advance, you can extend this setup to handle more complex real-time processing, database storage, and authentication.