0Pricing
Flask Academy · Lezione

Verificare route e JSON

Controlli i codici di stato e i corpi delle risposte.

Verificare route e JSON è 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.

What You Assert

A good route test checks two things: the right status code and the right body. If both match, you know the endpoint behaves as promised.

Check the Status Code

The response carries a status_code attribute. A healthy page returns 200, so assert on it to confirm the route loaded without error.

resp = client.get('/')
assert resp.status_code == 200

Read the Raw Body

The full response body lives in resp.data as bytes. Decode it to text when you want to search for words inside an HTML page.

body = resp.data.decode()
assert 'Welcome' in body

Assert Text Is Present

To confirm a page shows the right content, check that a phrase appears in the body. The simple in operator is perfect for this.

assert b'Welcome' in resp.data

Parse a JSON Response

For API routes, call resp.get_json(). Flask parses the body into a Python dict or list so you can assert on real values.

data = resp.get_json()
assert data['name'] == 'Ada'

Assert on Dict Keys

Once you have the parsed dict, check individual keys and values. This proves your serializer returned exactly the fields you expect.

data = resp.get_json()
assert data['id'] == 1
assert 'email' in data

Check the Content Type

A JSON endpoint should advertise itself. Assert that resp.content_type includes application/json so clients parse it correctly.

assert 'application/json' in resp.content_type

Test a 404 Route

Error paths deserve tests too. Request a missing URL and assert the status is 404, proving your app fails gracefully.

resp = client.get('/nope')
assert resp.status_code == 404

Test a POST Endpoint

Send data with client.post and a json argument. Then assert the created status code, usually 201, and the returned body.

resp = client.post('/items', json={'name': 'pen'})
assert resp.status_code == 201

Assert on a JSON List

Collection endpoints return a list. Parse it, then assert its length or inspect items by index to verify the payload shape.

items = resp.get_json()
assert len(items) == 3
assert items[0]['id'] == 1

One Behavior per Test

Keep each test focused on a single behavior. Small, named tests make failures obvious and your suite far easier to read.

Quick Check

You hit a JSON API route in a test. How do you read its body?

Recap: Routes and JSON

You now assert on status codes, page text, and parsed JSON. With these moves you can pin down any route's behavior with confidence. ✅

Domande Frequenti

La lezione «Verificare route e JSON» è gratuita?

Sì — il testo completo di «Verificare route e JSON» è 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 «Verificare route e JSON»?

Controlli i codici di stato e i corpi delle risposte. 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 «Verificare route e JSON»?

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. Test client e fixture
  2. Verificare route e JSON
  3. Isolare i test con un database di test
  4. Testare gli endpoint autenticati
← Torna a Flask Academy