Bird
Raised Fist0
Rest APIprogramming~20 mins

Why testing validates contracts in Rest API - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
API Contract Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when the API returns unexpected data?

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"}?

Rest API
response = {"status": "error", "message": "Invalid request"}
if response.get("status") == "success":
    print("Contract validated: success")
else:
    print("Contract violation detected")
AContract violation detected
BContract validated: success
CKeyError exception
DNo output
Attempts:
2 left
💡 Hint

Check the value of the status key in the response dictionary.

🧠 Conceptual
intermediate
2:00remaining
Why is testing important for API contracts?

Which of the following best explains why testing validates API contracts?

ATesting guarantees the API will never have bugs.
BTesting improves the API server's hardware performance.
CTesting ensures the API implementation matches the agreed request and response formats.
DTesting replaces the need for documentation.
Attempts:
2 left
💡 Hint

Think about what a contract means in API communication.

🔧 Debug
advanced
2:00remaining
Identify the error in this API contract test

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}?

Rest API
response = {"data": None}
if isinstance(response["data"], list):
    print("Valid data list")
else:
    print("Invalid data format")
AInvalid data format
BKeyError exception
CValid data list
DTypeError exception
Attempts:
2 left
💡 Hint

Check the type of response["data"] when it is None.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this API test code?

Which of the following code snippets will cause a syntax error when testing an API response?

Aif 'status' in response: print('OK')
Bif response.get('status') == 'success': print('OK')
Cif response.get('status') != 'error': print('OK')
Dif response['status'] = 'success': print('OK')
Attempts:
2 left
💡 Hint

Look for the assignment operator used inside the if condition.

🚀 Application
expert
3:00remaining
How many contract violations are detected in this batch test?

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"}
]
Rest API
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)
A1
B2
C3
D4
Attempts:
2 left
💡 Hint

Count how many responses have a status not equal to success.

Practice

(1/5)
1. Why is testing important for validating REST API contracts?
easy
A. It makes the API run faster by optimizing code.
B. It automatically generates API documentation.
C. It ensures the API follows agreed rules and behaves as expected.
D. It replaces the need for API design.

Solution

  1. Step 1: Understand the purpose of API contracts

    API contracts define rules about how APIs should behave and what data they exchange.
  2. Step 2: Role of testing in contracts

    Testing checks if the API follows these rules and returns expected results, catching mistakes early.
  3. Final Answer:

    It ensures the API follows agreed rules and behaves as expected. -> Option C
  4. Quick Check:

    Testing validates contracts = Ensures API rules followed [OK]
Hint: Testing checks if API follows rules and returns expected data [OK]
Common Mistakes:
  • Thinking testing speeds up API automatically
  • Confusing testing with documentation generation
  • Believing testing replaces API design
2. Which of the following is the correct way to test a REST API contract for a GET request?
easy
A. Send a DELETE request and expect a 500 error.
B. Send a POST request and check if the response status is 404.
C. Send a GET request and ignore the response content.
D. Send a GET request and check if the response status is 200 and data format matches the contract.

Solution

  1. Step 1: Identify correct HTTP method and expected response

    For a GET request, the API should return status 200 and data matching the contract.
  2. Step 2: Match testing action to contract validation

    Sending GET and checking status 200 plus data format confirms contract adherence.
  3. Final Answer:

    Send a GET request and check if the response status is 200 and data format matches the contract. -> Option D
  4. Quick Check:

    GET test checks status 200 and data format [OK]
Hint: Test GET by checking status 200 and correct data format [OK]
Common Mistakes:
  • Using wrong HTTP method for the test
  • Ignoring response content in tests
  • Expecting error codes for successful GET
3. Given this test code snippet for a REST API endpoint:
response = client.get('/users/123')
assert response.status_code == 200
assert 'id' in response.json()
assert response.json()['id'] == 123

What does this test validate about the API contract?
medium
A. The API returns status 200 and correct user id in JSON response.
B. The API returns status 404 for missing users.
C. The API accepts POST requests at /users/123.
D. The API returns an empty JSON response.

Solution

  1. Step 1: Analyze the test assertions

    The test checks that the response status code is 200 and the JSON response contains an 'id' key equal to 123.
  2. Step 2: Understand what this means for the API contract

    This confirms the API returns successful status and correct user data as per contract.
  3. Final Answer:

    The API returns status 200 and correct user id in JSON response. -> Option A
  4. Quick Check:

    Test checks status 200 and user id = 123 [OK]
Hint: Check status and key-value in JSON to validate contract [OK]
Common Mistakes:
  • Confusing status 404 with 200
  • Assuming POST method is tested here
  • Ignoring JSON content checks
4. A test for a REST API endpoint expects a JSON response with a 'name' field. The test code is:
response = client.get('/items/5')
assert response.status_code == 200
assert 'name' in response.json()

But the test fails with a KeyError. What is the likely cause?
medium
A. The response status code is not 200.
B. The API response JSON does not include the 'name' field as per contract.
C. The test used the wrong HTTP method.
D. The client.get() method is not defined.

Solution

  1. Step 1: Understand the test failure

    A KeyError means the 'name' key is missing in the JSON response.
  2. Step 2: Identify contract violation

    The API response does not include the expected 'name' field, violating the contract.
  3. Final Answer:

    The API response JSON does not include the 'name' field as per contract. -> Option B
  4. Quick Check:

    Missing 'name' key causes KeyError [OK]
Hint: KeyError means expected JSON key missing in response [OK]
Common Mistakes:
  • Assuming wrong HTTP method caused error
  • Ignoring status code correctness
  • Blaming client.get() method existence
5. You have a REST API contract that requires the endpoint /orders/{id} to return a JSON with fields id, status, and items (a list). Which test best validates this contract?
hard
A. Send GET /orders/10, check status 200, verify JSON has 'id', 'status', and 'items' keys, and 'items' is a list.
B. Send POST /orders with empty body and expect status 201.
C. Send GET /orders/10 and check only the status code is 404.
D. Send DELETE /orders/10 and expect status 500.

Solution

  1. Step 1: Identify contract requirements

    The contract requires GET /orders/{id} to return JSON with 'id', 'status', and 'items' keys, where 'items' is a list.
  2. Step 2: Match test to contract validation

    Sending GET /orders/10, checking status 200, verifying JSON has 'id', 'status', and 'items' keys, and confirming 'items' is a list fully validates the contract.
  3. Final Answer:

    Send GET /orders/10, check status 200, verify JSON has 'id', 'status', and 'items' keys, and 'items' is a list. -> Option A
  4. Quick Check:

    Test checks all required fields and types [OK]
Hint: Check all required fields and data types in JSON response [OK]
Common Mistakes:
  • Testing wrong HTTP method
  • Ignoring required JSON fields
  • Not verifying data types like list
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard