Bird
0
0

Given this Python Flask code snippet for a REST API endpoint:

medium📝 Debug Q14 of 15
Rest API - HTTP Status Codes

Given this Python Flask code snippet for a REST API endpoint:

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Missing name field'}), 400
    return jsonify({'message': f"Hello, {data['name']}!"})

What is the likely cause of a 400 Bad Request response?

AThe server returned a success message.
BThe client sent a POST request without JSON body or missing 'name' key.
CThe client used GET method instead of POST.
DThe server crashed due to a syntax error.
Step-by-Step Solution
Solution:
  1. Step 1: Check the condition triggering 400 response

    The code returns 400 if JSON data is missing or 'name' key is absent.
  2. Step 2: Understand when this happens

    If client sends no JSON or JSON without 'name', server responds with 400 Bad Request.
  3. Final Answer:

    The client sent a POST request without JSON body or missing 'name' key. -> Option B
  4. Quick Check:

    Missing JSON or 'name' key triggers 400 [OK]
Quick Trick: 400 occurs if required JSON field is missing [OK]
Common Mistakes:
MISTAKES
  • Assuming server crashed
  • Confusing HTTP methods
  • Thinking 400 means success

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes