Consider a REST API client that expects a JSON response with a status field set to success. The client tests the response to validate the contract.
What will be the output of the following code if the API returns {"status": "error", "message": "Invalid request"}?
response = {"status": "error", "message": "Invalid request"}
if response.get("status") == "success":
print("Contract validated: success")
else:
print("Contract violation detected")Check the value of the status key in the response dictionary.
The code checks if the status key equals success. Since the API returned error, the else branch runs, printing "Contract violation detected".
Which of the following best explains why testing validates API contracts?
Think about what a contract means in API communication.
API contracts define how clients and servers communicate. Testing checks that the API behaves as promised, matching the contract's request and response formats.
The following test checks if the API response contains a data field with a list. What error will this code produce if the API returns {"data": null}?
response = {"data": None}
if isinstance(response["data"], list):
print("Valid data list")
else:
print("Invalid data format")Check the type of response["data"] when it is None.
The code checks if response["data"] is a list. Since it is None, the else branch runs, printing "Invalid data format". No exception occurs.
Which of the following code snippets will cause a syntax error when testing an API response?
Look for the assignment operator used inside the if condition.
Option D uses = (assignment) instead of == (comparison) inside the if condition, causing a syntax error.
Given the following list of API responses, how many violate the contract that requires status to be success?
responses = [
{"status": "success", "data": [1,2]},
{"status": "error", "message": "fail"},
{"status": "success", "data": []},
{"status": "pending"}
]responses = [
{"status": "success", "data": [1,2]},
{"status": "error", "message": "fail"},
{"status": "success", "data": []},
{"status": "pending"}
]
violations = 0
for r in responses:
if r.get("status") != "success":
violations += 1
print(violations)Count how many responses have a status not equal to success.
Two responses have status values other than success: "error" and "pending". So, violations = 2.