──────────────────────────────────────

45. Work with Web Data · Read a Saved JSON Response

Check a response status before turning its JSON body into Python values.

Lesson files · lessons/web-data/json-response

Before you start
- Load a JSON object into a dictionary.
- Use len() to count entries in a list and a branch to pick an output.

By the end
- Read a saved response and count bookings after a 200 status.
- Explain how a successful empty list and a failed response appear in the output.

Where you can use it
Inspect a saved booking response to decide whether to show a booking count or report a service failure.

HTTP is how a client requests data and a web server replies. An API gives programs a documented way to ask for data. A response has a status code describing the result and may carry a body with the data. A 200 status means the request succeeded. A 503 status means the service is temporarily unavailable. Check for 200 before calling json.loads() on the body. An error response can contain text or HTML. A saved example of a response is called a fixture. These fictional fixtures let you practise offline with the same input every time.

Predict
What happens if status changes to 503 and body changes to Service unavailable?
- It prints HTTP 503.
- It tries to decode the error text as JSON.

Worked example (example.py)

import json

status = 200
body = '{"room": "Library", "open": true}'
if status == 200:
    notice = json.loads(body)
    print(notice["room"])
else:
    print(f"HTTP {status}")


Example result
Library

Read the status code and the response body on two lines. For status 200, parse the JSON body and print Bookings: followed by the number of objects in the bookings list. For every other status, print HTTP followed by the numeric code. For example, HTTP 503.

Starter program (starter.py)

status = int(input())
body = input()
print(f"Received status {status}")


Starter input
200
{"bookings":[{"slot":"10:00"},{"slot":"11:00"}]}

Hint
Use int(input()) for the status and len(data["bookings"]) for the count.

Case 1. Try the sample
Input
200
{"bookings":[{"slot":"10:00"},{"slot":"11:00"}]}
Expected output
Bookings: 2

Case 2. Empty list
Input
200
{"bookings":[]}
Expected output
Bookings: 0

Case 3. Service unavailable
Input
503
Please try again later.
Expected output
HTTP 503

Stretch
For a successful response, print each booking time after the total.

Reflect
Why would an empty bookings list and a 503 status mean different things to the club organiser?

Check your prediction
It prints HTTP 503. The program only reads the body as JSON when the status is 200.
