0
0
Rest APIprogramming~10 mins

422 Unprocessable Entity in Rest API - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return a 422 status when the input data is invalid.

Rest API
if not valid_data:
    return {'error': 'Invalid input'}, [1]
Drag options to blanks, or click blank then click option'
A422
B404
C200
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 instead of 422 for invalid input.
Returning 200 OK even when input is invalid.
2fill in blank
medium

Complete the code to check for missing required fields and respond with 422.

Rest API
required_fields = ['name', 'email']
if any(field not in data for field in [1]):
    return {'error': 'Missing fields'}, 422
Drag options to blanks, or click blank then click option'
Arequired_fields
Bfields
Crequest
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Checking keys in the wrong variable.
Using the data variable instead of the list of required fields.
3fill in blank
hard

Fix the error in the code to correctly return a 422 response with a JSON error message.

Rest API
def handle_request(data):
    if not is_valid(data):
        return [1]
Drag options to blanks, or click blank then click option'
Areturn 422
B({'error': 'Invalid data'}, 422)
C422, {'error': 'Invalid data'}
Djsonify({'error': 'Invalid data'}), 422
Attempts:
3 left
💡 Hint
Common Mistakes
Returning status code before the response body.
Not using a JSON formatter function.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that filters valid fields and returns 422 if any are missing.

Rest API
filtered_data = {field: data[field] for field in data if field [1] required_fields}
if len(filtered_data) [2] len(required_fields):
    return {'error': 'Missing required fields'}, 422
Drag options to blanks, or click blank then click option'
Ain
B==
C<
Dnot in
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'not in' instead of 'in' in the comprehension.
Using '==' instead of '<' to check missing fields.
5fill in blank
hard

Fill all three blanks to create a function that validates input and returns 422 with a message if invalid.

Rest API
def validate_input(data):
    errors = {field: 'Required' for field in [1] if field not in [2]
    if errors:
        return [3], 422
    return None
Drag options to blanks, or click blank then click option'
Arequired_fields
Bdata
C{'errors': errors}
Dfields
Attempts:
3 left
💡 Hint
Common Mistakes
Checking fields in the wrong variable.
Returning errors without wrapping in a dictionary.