201 Status Code: Meaning and Usage in REST APIs
201 status code means "Created" in REST APIs. It indicates that a request has successfully created a new resource, and the server usually returns the location of that resource.How It Works
When you send a request to create something new on a server, like adding a new user or posting a comment, the server processes your request. If everything goes well and the new item is created, the server responds with a 201 Created status code.
This code tells you that your action worked and a new resource now exists. Often, the server also sends back a link (URL) where you can find or access this new resource, similar to getting a receipt with a tracking number after ordering a package.
Example
This example shows a simple REST API endpoint in Python using Flask that creates a new user and returns a 201 status code with the location of the new user.
from flask import Flask, request, jsonify, url_for app = Flask(__name__) users = {} @app.route('/users', methods=['POST']) def create_user(): user_id = len(users) + 1 user_data = request.json users[user_id] = user_data location = url_for('get_user', user_id=user_id, _external=True) response = jsonify({'id': user_id, 'user': user_data}) response.status_code = 201 response.headers['Location'] = location return response @app.route('/users/<int:user_id>') def get_user(user_id): user = users.get(user_id) if user: return jsonify({'id': user_id, 'user': user}) return jsonify({'error': 'User not found'}), 404 if __name__ == '__main__': app.run(debug=True)
When to Use
Use the 201 status code whenever your API successfully creates a new resource in response to a client request. This is common in POST requests where new data is added.
For example, when a user signs up on a website, the server creates a new user record and should respond with 201 Created and the URL to access that user. This helps clients know the creation was successful and where to find the new resource.
Key Points
- 201 means a new resource was created successfully.
- The response usually includes a
Locationheader with the URL of the new resource. - It is mainly used in response to
POSTrequests. - It helps clients confirm creation and find the new resource.