Bird
0
0

You have an API that returns a list of products, each with 'id' and 'price'. How would you write a test to validate the contract that all products have these fields?

hard📝 Application Q9 of 15
Rest API - API Testing and Monitoring
You have an API that returns a list of products, each with 'id' and 'price'. How would you write a test to validate the contract that all products have these fields?
Aassert all(response.json()['id']) and all(response.json()['price'])
Bfor p in response.json(): assert 'id' in p and 'price' in p
Cassert response.json()['id'] and response.json()['price']
Dassert 'id' in response.json() and 'price' in response.json()
Step-by-Step Solution
Solution:
  1. Step 1: Understand response structure

    Response is a list of product dictionaries.
  2. Step 2: Validate each product has required keys

    Loop through each product and assert presence of 'id' and 'price'.
  3. Final Answer:

    for p in response.json(): assert 'id' in p and 'price' in p -> Option B
  4. Quick Check:

    Loop through list to check keys in each item [OK]
Quick Trick: Loop over list to check keys in each dictionary [OK]
Common Mistakes:
MISTAKES
  • Checking keys on the whole list instead of items
  • Assuming keys exist at top-level list
  • Using all() incorrectly on keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes