0
0
Rest APIprogramming~10 mins

Content negotiation 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 set the response content type to JSON.

Rest API
response.headers['Content-Type'] = '[1]'
Drag options to blanks, or click blank then click option'
Atext/html
Btext/plain
Capplication/json
Dapplication/xml
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'text/html' instead of 'application/json' for JSON responses.
Forgetting to set the Content-Type header.
2fill in blank
medium

Complete the code to check if the client accepts JSON responses.

Rest API
if 'application/json' in request.headers.get('[1]', ''):
Drag options to blanks, or click blank then click option'
AContent-Type
BAccept
CAuthorization
DUser-Agent
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'Content-Type' header instead of 'Accept'.
Not handling the case when the header is missing.
3fill in blank
hard

Fix the error in the code to correctly parse the client's preferred content type.

Rest API
preferred = request.headers.get('Accept', '').split(',')[[1]].strip()
Drag options to blanks, or click blank then click option'
A2
B1
C-1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 instead of 0, causing an error if only one type is present.
Using negative index which may not be intended here.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps content types to their quality values from the Accept header.

Rest API
qualities = {ctype: float(q.split('=')[1]) if 'q=' in q else 1.0 for ctype, q in (item.split(';')[1] for item in request.headers.get('Accept', '').split(',')) if ctype [2] ''}
Drag options to blanks, or click blank then click option'
A if len(item.split(';')) > 1 else ''
B!=
C==
D else None
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' in the filter condition.
Not handling items without quality values properly.
5fill in blank
hard

Fill all three blanks to return the best matching content type from the server's supported types based on client's Accept header.

Rest API
def best_match(supported_types):
    qualities = {ctype: float(q.split('=')[1]) if 'q=' in q else 1.0 for ctype, q in (item.split(';')[1] for item in request.headers.get('Accept', '').split(',')) if ctype [2] ''}
    best = max(supported_types, key=lambda t: qualities.get(t, [3]))
    return best
Drag options to blanks, or click blank then click option'
A if len(item.split(';')) > 1 else ''
B!=
C0
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '!=' in the filter.
Using None or other values instead of 0 as default quality.