What is 400 Status Code: Meaning and Usage in REST APIs
400 status code means "Bad Request" in REST APIs. It tells the client that the server cannot process the request because it is malformed or invalid.How It Works
Imagine you are sending a letter to a friend, but the letter is missing important information or has unclear instructions. Your friend might not understand what you want and will ask you to fix it. In REST APIs, the 400 Bad Request status code works the same way. It tells the client that the server cannot understand the request because it is incorrect or incomplete.
This status code is sent by the server when the request syntax is wrong, required data is missing, or the data format is invalid. It helps the client know that the problem is with the request itself, not the server.
Example
This example shows a simple REST API endpoint in Python using Flask. If the client sends a request without the required "name" field, the server responds with a 400 status code and an error message.
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/greet', methods=['POST']) def greet(): 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"]}!'}), 200 if __name__ == '__main__': app.run(debug=True)
When to Use
Use the 400 Bad Request status code when the client sends a request that the server cannot process due to client errors. This includes:
- Missing required fields in the request data
- Invalid data formats (e.g., sending text instead of a number)
- Malformed JSON or incorrect syntax
For example, if a user submits a form without filling all required fields, the server should respond with a 400 status code to indicate the problem is with the request.
Key Points
- 400 status code means the request is invalid or malformed.
- It signals a client-side error, not a server problem.
- Helps clients fix their requests before retrying.
- Commonly used for missing data, wrong formats, or syntax errors.