0Pricing
Flask Academy · Lezione

Endpoint per leggere uno o più elementi

Restituisca un singolo elemento o una raccolta.

Endpoint per leggere uno o più elementi è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 2 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 Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Two Shapes of Read

A REST resource needs two read endpoints: one that returns a single item by id, and one that returns the whole collection. 📚

List Route for Many

The collection lives at a plain path like /users. A GET there should answer with every matching record.

@app.route("/users")
def list_users():
    ...

Load Them All

Fetch the full set with query.all(), which gives you a Python list of model instances to serialize.

users = User.query.all()

Serialize the Collection

jsonify cannot dump model objects directly, so map each row to a dict first, then return the list.

return jsonify([{"id": u.id, "name": u.name} for u in users])

Detail Route for One

A single item lives at /users/<id>. The id in the path tells you exactly which row to load.

@app.route("/users/<int:user_id>")
def get_user(user_id):
    ...

Fetch That One Row

Use get() with the path id to pull the matching record straight from the database.

user = User.query.get(user_id)

Return the Single Item

Wrap the found row in a dict and jsonify it. Your client gets one clean JSON object back.

return jsonify({"id": user.id, "name": user.name})

Handle the Missing Case

If get returns None, the id was wrong, so reply with a 404 instead of crashing on a None value.

if user is None:
    return jsonify(error="not found"), 404

Skip the Check with get_or_404

Flask-SQLAlchemy's get_or_404() fetches by id or aborts with 404 automatically, trimming the boilerplate from detail views.

user = User.query.get_or_404(user_id)

Paginate Long Lists

Returning thousands of rows is slow. Use paginate() to slice the collection into pages your client can request one at a time.

page = User.query.paginate(page=1, per_page=20)

List Returns an Array

Keep shapes predictable: the collection route returns a JSON array, while the detail route returns a single object.

Quick Check

A request hits /users/42 but no such row exists. What should the endpoint do?

Recap: Reading Records

You built a list route returning an array and a detail route returning one item, with 404 for missing rows. Reads done right! 🎉

Domande Frequenti

La lezione «Endpoint per leggere uno o più elementi» è gratuita?

Sì — il testo completo di «Endpoint per leggere uno o più elementi» è 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 Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «Endpoint per leggere uno o più elementi»?

Restituisca un singolo elemento o una raccolta. Eserciti Flask Academy 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 Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Endpoint per leggere uno o più elementi»?

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 Flask Academy?

Sì. Ogni lezione Flask Academy 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

  1. Creare record e fare il commit delle sessioni
  2. Endpoint per leggere uno o più elementi
  3. Aggiornare in sicurezza i record esistenti
  4. Eliminare e gestire le righe mancanti
← Torna a Flask Academy