π Tutorial: Your First API in 5 Minutes¶
In this tutorial, we will build a simple βGreeting APIβ using pico-fastapi. You will learn how to define services, create controllers, and wire everything together using the container.
π‘ Recommended: Use
pico-bootfor auto-discovery and zero-config bootstrapping. If you are not usingpico-boot, see the Classic Version (without pico-boot) linked below.
β Prerequisites¶
Install all required packages:
π Step 1: Define your Service¶
# services.py
from pico_ioc import component
@component
class GreeterService:
def greet(self, name: str) -> str:
return f"Hello, {name}! Welcome to pico-fastapi."
π Step 2: Create a Controller¶
# controllers.py
from pico_fastapi import controller, get
from services import GreeterService
@controller(prefix="/greet")
class GreeterController:
def __init__(self, service: GreeterService):
self.service = service
@get("/{name}")
async def say_hello(self, name: str):
return {"message": self.service.greet(name)}
π Step 3: Wire the Application (Using pico-boot)¶
With pico-boot, pico-fastapi is automatically discovered via entry points. You only need to list your modules.
# main.py
from fastapi import FastAPI
from pico_boot import init
def create_app() -> FastAPI:
container = init(
modules=[
"controllers",
"services",
]
)
return container.get(FastAPI)
app = create_app()
β No "pico_fastapi" β Auto-loaded β Cleaner, safer bootstrapping
π Step 4: Run It¶
Then open: π http://127.0.0.1:8000/docs
You will see the automatically generated Swagger UI with your /greet/{name} endpoint.
π‘ Key Takeaways¶
-
Clear separation of concerns Your services contain pure business logicβnot framework code.
-
Constructor injection Dependencies are explicit in
__init__, fully managed by Pico-IoC. -
No global state Scopes are created and cleaned up automatically via fastapi middleware.
-
Auto-discovery with pico-boot Your modules stay clean; pico-fastapi loads itself automatically.
π Classic Version (Without pico-boot)¶
If you want the version that uses only pico_ioc.init(), you can find it here:
π Classic Tutorial (init + manual module declaration) https://github.com/dperezcabrera/pico-fastapi/blob/main/docs/tutorial-classic.md (or wherever you want to place it; I can generate the file for you)
The only change in the classic version is: