0
0
Rest APIprogramming~5 mins

200 OK and 201 Created in Rest API

Choose your learning style9 modes available
Introduction

These status codes tell you if your request to a web server worked. They help you understand what happened after you sent data or asked for something.

When you successfully get data from a server, like loading a webpage or fetching user info.
When you send new data to a server and it creates something new, like signing up for a new account.
When you update existing data and want to confirm it worked without creating anything new.
When you want to know if your request was successful and what kind of success it was.
Syntax
Rest API
HTTP/1.1 200 OK

HTTP/1.1 201 Created

200 OK means the request was successful and the server sent back the requested data or confirmation.

201 Created means the request was successful and the server created a new resource as a result.

Examples
This shows a successful response with data sent back to the client.
Rest API
HTTP/1.1 200 OK
Content-Type: application/json

{"name": "Alice", "age": 30}
This shows a new user was created and the server tells where to find it.
Rest API
HTTP/1.1 201 Created
Location: /users/123

{"id": 123, "name": "Bob"}
Sample Program

This simple web server has two routes: one to get all users with a 200 OK response, and one to add a new user with a 201 Created response.

Rest API
from flask import Flask, jsonify, request

app = Flask(__name__)

users = []

@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(users), 200

@app.route('/users', methods=['POST'])
def create_user():
    user = request.json
    user['id'] = len(users) + 1
    users.append(user)
    return jsonify(user), 201

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Use 200 OK when you return data or confirm a successful action without creating new resources.

Use 201 Created when your request results in a new resource being made on the server.

Always include useful information in the response body or headers to help the client understand what happened.

Summary

200 OK means success and data or confirmation is sent back.

201 Created means success and a new resource was created.

These codes help clients know how their requests were handled.