Structuring a project
I need to outline how to structure a project, with a suggested layout like this:
project/
main.py
requirements.txt
It could be helpful to include a sample requirements file. The user might expect "Build" to mean providing clear environment instructions like using pip to install dependencies and then running the code. So, I’ll make sure everything is syntactically correct as I assemble the answer and craft the necessary code.Creating the IoT Device Manager API
I’m working on a FastAPI project to manage IoT devices. The structure includes several classes like DeviceBase, DeviceCreate, and DeviceUpdate, which define the properties of devices.
I need to ensure the routes are efficient, enabling operations like registering devices, listing them, updating their status, and sending commands. Each route needs proper error handling and should accurately manage device state. I’ll also make sure to test everything to ensure the code works smoothly.Finalizing the API project setup
I'm working on the command handling for devices in my FastAPI project. The endpoint to list commands for a device needs to check for existence first, raising a 404 if the device isn't found.
Next, I should finalize the requirements.txt file. I believe it should just list fastapi and uvicorn[standard] without pinning versions, since that could lead to inaccuracies. I’ll include a note about running the app with uvicorn main:app --reload and provide a sample CURL command for users, plus mention migrating to a real database with SQLAlchemy or PostgreSQL later.Crafting a concise project overview
The user’s request seems open-ended, so I think it makes sense to provide some brief explanation about RESTful design and the endpoints. However, I want to keep it concise. I’ll start with a short bullet list outlining the design, followed by the code, and then explain how to run and extend it.
I might mention a basic folder structure for organizing the project, like having an iot_manager/ directory with subfolders for models, schemas, and routers. But I won’t overcomplicate things since they asked for a simple one-file version and I should suggest ways to modularize later on. Here is a minimal but complete Python application using FastAPI that exposes RESTful APIs to manage IoT devices (register, list, update, delete, send commands, heartbeat).
1. Project setup
Directory structure
iot-device-manager/
├─ main.py
└─ requirements.txt
requirements.txt
fastapi
uvicorn[standard]
Install dependencies:
cd iot-device-manager
pip install -r requirements.txt
2. Application code (main.py)
from datetime import datetime
from typing import Optional, Dict, List, Any
import uuid
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(
title="IoT Device Manager API",
version="1.0.0",
description="RESTful API to manage IoT devices, heartbeat, and commands",
)
# -----------------------------
# Pydantic models (schemas)
# -----------------------------
class DeviceBase(BaseModel):
name: str = Field(..., example="Living Room Sensor")
device_type: str = Field(..., example="temperature_sensor")
firmware_version: Optional[str] = Field(None, example="1.0.3")
status: str = Field("offline", example="online")
metadata: Dict[str, Any] = Field(
default_factory=dict,
example={"location": "living_room"},
)
class DeviceCreate(DeviceBase):
"""Fields required when creating a device."""
pass
class DeviceUpdate(BaseModel):
"""Fields that can be updated (all optional)."""
name: Optional[str] = None
device_type: Optional[str] = None
firmware_version: Optional[str] = None
status: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
class Device(DeviceBase):
"""Device representation returned by the API."""
id: str
registered_at: datetime
last_seen: Optional[datetime] = None
class CommandRequest(BaseModel):
command: str = Field(..., example="reboot")
params: Dict[str, Any] = Field(
default_factory=dict,
example={"delay_seconds": 5},
)
class CommandResponse(BaseModel):
device_id: str
command: str
params: Dict[str, Any]
accepted: bool
queued_at: datetime
# -----------------------------
# In-memory "database"
# -----------------------------
devices: Dict[str, Device] = {}
commands_queue: Dict[str, List[CommandResponse]] = {}
# -----------------------------
# Device CRUD endpoints
# -----------------------------
@app.post("/devices", response_model=Device, status_code=201)
def register_device(device_in: DeviceCreate):
"""
Register a new IoT device.
"""
device_id = str(uuid.uuid4())
now = datetime.utcnow()
device = Device(
id=device_id,
registered_at=now,
last_seen=None,
**device_in.dict(),
)
devices[device_id] = device
return device
@app.get("/devices", response_model=List[Device])
def list_devices():
"""
List all registered devices.
"""
return list(devices.values())
@app.get("/devices/{device_id}", response_model=Device)
def get_device(device_id: str):
"""
Get details of a single device by ID.
"""
device = devices.get(device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
return device
@app.put("/devices/{device_id}", response_model=Device)
def replace_device(device_id: str, device_in: DeviceCreate):
"""
Replace a device's information (full update).
"""
existing = devices.get(device_id)
if not existing:
raise HTTPException(status_code=404, detail="Device not found")
updated = existing.copy(update=device_in.dict())
devices[device_id] = updated
return updated
@app.patch("/devices/{device_id}", response_model=Device)
def update_device(device_id: str, device_in: DeviceUpdate):
"""
Partially update a device (only provided fields).
"""
existing = devices.get(device_id)
if not existing:
raise HTTPException(status_code=404, detail="Device not found")
update_data = device_in.dict(exclude_unset=True)
updated = existing.copy(update=update_data)
devices[device_id] = updated
return updated
@app.delete("/devices/{device_id}", status_code=204)
def delete_device(device_id: str):
"""
Delete a device.
"""
if device_id not in devices:
raise HTTPException(status_code=404, detail="Device not found")
devices.pop(device_id)
commands_queue.pop(device_id, None)
return # FastAPI will return 204 No Content
# -----------------------------
# Heartbeat & status endpoints
# -----------------------------
@app.post("/devices/{device_id}/heartbeat", response_model=Device)
def device_heartbeat(device_id: str, status: Optional[str] = None):
"""
Device heartbeat: updates last_seen timestamp and optionally status.
"""
device = devices.get(device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
update_data = {"last_seen": datetime.utcnow()}
if status:
update_data["status"] = status
updated = device.copy(update=update_data)
devices[device_id] = updated
return updated
# -----------------------------
# Command endpoints
# -----------------------------
@app.post("/devices/{device_id}/commands", response_model=CommandResponse, status_code=202)
def send_command(device_id: str, cmd: CommandRequest):
"""
Send a command to a device (queued for later delivery).
"""
if device_id not in devices:
raise HTTPException(status_code=404, detail="Device not found")
queued = CommandResponse(
device_id=device_id,
command=cmd.command,
params=cmd.params,
accepted=True,
queued_at=datetime.utcnow(),
)
commands_queue.setdefault(device_id, []).append(queued)
return queued
@app.get("/devices/{device_id}/commands", response_model=List[CommandResponse])
def list_device_commands(device_id: str):
"""
List commands queued for a specific device.
"""
if device_id not in devices:
raise HTTPException(status_code=404, detail="Device not found")
return commands_queue.get(device_id, [])
3. Run the API server
From the project root:
uvicorn main:app --reload
The API will be available at:
- Base URL:
http://127.0.0.1:8000
- Interactive docs (Swagger UI):
http://127.0.0.1:8000/docs
- OpenAPI JSON:
http://127.0.0.1:8000/openapi.json
4. Example usage (with curl)
Register a device
curl -X POST "http://127.0.0.1:8000/devices" \
-H "Content-Type: application/json" \
-d '{
"name": "Living Room Sensor",
"device_type": "temperature_sensor",
"firmware_version": "1.0.3",
"status": "online",
"metadata": {"location": "living_room"}
}'
The response will include an id you can use next.
Send a heartbeat
curl -X POST "http://127.0.0.1:8000/devices/<DEVICE_ID>/heartbeat?status=online"
Send a command
curl -X POST "http://127.0.0.1:8000/devices/<DEVICE_ID>/commands" \
-H "Content-Type: application/json" \
-d '{"command": "reboot", "params": {"delay_seconds": 10}}'
5. How to extend this
For a production-ready IoT device manager, you would typically add:
- A real database (PostgreSQL, MySQL, etc.) using SQLAlchemy or similar instead of the in-memory dicts.
- Authentication/authorization (e.g., API keys, OAuth2/JWT).
- Pagination, filtering, and sorting for
/devices.
- Background workers for actually delivering commands to devices via MQTT, AMQP, or another protocol.
- Proper logging, metrics, and error handling.
If you tell me your preferred stack (e.g., PostgreSQL, MQTT, auth method), I can extend this example accordingly.