When to Use Which HTTP Status Code: Clear Guide for REST APIs
200 OK for successful requests, 201 Created when a new resource is made, 400 Bad Request for client errors, 401 Unauthorized for missing or invalid authentication, and 404 Not Found when a resource doesn't exist. Choose status codes that clearly communicate the result of the API call to the client.How It Works
HTTP status codes are like traffic signals for web communication. They tell the client (like a browser or app) what happened after it sent a request to the server. Just like a green light means go and a red light means stop, status codes guide the client on what to do next.
When you call an API, the server responds with a status code that shows if the request was successful, if there was a problem with the request, or if something went wrong on the server. This helps the client understand if it should show data, ask the user to fix something, or try again later.
Example
This example shows a simple REST API endpoint in Python using Flask that returns different status codes based on the request.
from flask import Flask, jsonify, request app = Flask(__name__) items = {"1": "apple", "2": "banana"} @app.route('/items/<item_id>', methods=['GET']) def get_item(item_id): if item_id in items: return jsonify({"item": items[item_id]}), 200 # OK else: return jsonify({"error": "Item not found"}), 404 # Not Found @app.route('/items', methods=['POST']) def create_item(): data = request.get_json() if not data or 'name' not in data: return jsonify({"error": "Bad request, 'name' is required"}), 400 # Bad Request new_id = str(len(items) + 1) items[new_id] = data['name'] return jsonify({"id": new_id, "name": data['name']}), 201 # Created if __name__ == '__main__': app.run(debug=True)
When to Use
Use 200 OK when a request is successful and you return the requested data.
Use 201 Created after successfully creating a new resource, like adding a new user or item.
Use 400 Bad Request when the client sends data that is missing required fields or is malformed.
Use 401 Unauthorized when the client needs to authenticate or provide valid credentials.
Use 403 Forbidden when the client is authenticated but does not have permission to access the resource.
Use 404 Not Found when the requested resource does not exist on the server.
Use 500 Internal Server Error when something unexpected fails on the server side.
Choosing the right status code helps clients handle responses correctly and improves API clarity.
Key Points
- 200 means success with data returned.
- 201 means a new resource was created.
- 400 means the client sent bad data.
- 401 means authentication is needed or failed.
- 404 means the resource was not found.
- 500 means a server error happened.