0Pricing
Flask Academy · Aula

Verifique rotas e JSON

Confira códigos de status e corpos de resposta.

Verifique rotas e JSON é uma aula grátis de Flask Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Flask Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Flask Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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. ✅

Perguntas Frequentes

A aula “Verifique rotas e JSON” é grátis?

Sim — o texto completo de “Verifique rotas e JSON” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Flask Academy, atualize para CoddyKit PRO. O curso de Flask Academy inclui 4 aulas no total.

O que vou aprender em “Verifique rotas e JSON”?

Confira códigos de status e corpos de resposta. Você pratica Flask Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Flask Academy?

Nenhuma experiência prévia é necessária. Flask Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Verifique rotas e JSON”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Flask Academy?

Sim. Cada aula de Flask Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. O cliente de testes e os dispositivos de teste
  2. Verifique rotas e JSON
  3. Isole testes com um banco de dados de teste
  4. Teste endpoints autenticados
← Voltar para Flask Academy