Parametri di path e query
Comprenda come acquisire dati dinamici dagli URL usando i parametri di path e come elaborare i parametri di query facoltativi.
Parametri di path e query è una lezione FastAPI Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento FastAPI Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Dynamic URLs for APIs
APIs often carry data right in the URL — fetching a product by ID or filtering a list. FastAPI gives you clean ways to capture that. Let's dig in.
Meet Path Parameters
Path parameters are URL segments that pin down a specific resource, written in curly braces like /items/{item_id}. Perfect for one exact item.
Your First Path Parameter
Match a path segment to a function arg by name: /items/{item_id} maps to item_id. The type hint int auto-converts it.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "message": "Here is your item!"}Power of Type Hints
Type hints like item_id: int drive validation. Hit /items/abc and FastAPI returns a clean error automatically. Use str, int, float, bool, UUID.
Handling Multiple Paths
You can take several path parameters in one route. FastAPI matches them by name, so the order in your function signature doesn't matter.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: str):
return {"user_id": user_id, "item_id": item_id}What are Query Parameters?
Query parameters are key-value pairs after a ?, like /items?skip=0&limit=10. They are optional — ideal for filtering, paging, or sorting.
Your First Query Parameter
Any function arg that is not in the path becomes a query parameter automatically. Here, skip and limit are typed integers.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}Optional Queries & Defaults
Make a query parameter optional by giving it a default. For a None default, type it as Optional[str] so FastAPI knows it may be missing.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/products/")
async def read_products(q: Optional[str] = None, page_size: int = 20):
results = {"page_size": page_size}
if q:
results.update({"search_query": q})
return resultsPath + Query Power
Combine both: path parameters are required, query parameters stay optional with defaults. FastAPI sorts out which is which seamlessly.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/orders/")
async def get_user_orders(user_id: int, status: Optional[str] = None, limit: int = 10):
return {"user_id": user_id, "status": status, "limit": limit, "message": "User orders fetched."}Quick Check on Parameters
Consider the following FastAPI endpoint:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/books/{book_id}")
async def get_book(book_id: int, author: str = "Unknown", published_year: Optional[int] = None):
return {
"book_id": book_id,
"author": author,
"published_year": published_year
}Which of the following URLs would successfully call this endpoint and return a published_year?
Recap: Dynamic API Routes
Great work! You made routes dynamic with path parameters for required IDs, query parameters for optional filters, and type hints for free validation.
Impara FastAPI Backend Development Bootcamp con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 21
- Lezioni
- 84
Domande Frequenti
La lezione «Parametri di path e query» è gratuita?
Sì — il testo completo di «Parametri di path e query» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso FastAPI Backend Development Bootcamp, passa a CoddyKit PRO. Il corso FastAPI Backend Development Bootcamp include 4 lezioni in totale.
Cosa imparerò in «Parametri di path e query»?
Comprenda come acquisire dati dinamici dagli URL usando i parametri di path e come elaborare i parametri di query facoltativi. Eserciti FastAPI Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare FastAPI Backend Development Bootcamp?
Non è richiesta alcuna esperienza precedente. FastAPI Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.
Quanto tempo richiede la lezione «Parametri di path e query»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione FastAPI Backend Development Bootcamp?
Sì. Ogni lezione FastAPI Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Introduzione a FastAPI e configurazione
- Il suo primo endpoint API
- Parametri di path e query
- Documentazione API interattiva con Swagger UI