0
0
Rest APIprogramming~5 mins

409 Conflict in Rest API

Choose your learning style9 modes available
Introduction

The 409 Conflict status code tells the client that the request could not be completed because it conflicts with the current state of the server. It helps avoid problems when two things try to change the same data at the same time.

When two users try to update the same record at the same time.
When a client tries to create a resource that already exists.
When a request would cause a duplicate entry in a database.
When a version conflict happens during data synchronization.
When a request violates a rule that prevents conflicting changes.
Syntax
Rest API
HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "error": "Conflict",
  "message": "Description of the conflict"
}
The status code 409 is sent in the HTTP response status line.
The response body usually explains what caused the conflict.
Examples
This response tells the client that the email they tried to use is already taken.
Rest API
HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "error": "Conflict",
  "message": "User with this email already exists."
}
This response warns that the document changed since the client last fetched it.
Rest API
HTTP/1.1 409 Conflict
Content-Type: application/json

{
  "error": "Conflict",
  "message": "The document has been modified by another user."
}
Sample Program

This simple Flask app simulates user registration. If the email is already in the 'database', it returns a 409 Conflict with a clear message. Otherwise, it registers the user.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

# Simulated database
users = {"alice@example.com": {"name": "Alice"}}

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    email = data.get('email')
    if email in users:
        return jsonify({"error": "Conflict", "message": "User with this email already exists."}), 409
    users[email] = {"name": data.get('name')}
    return jsonify({"message": "User registered successfully."}), 201

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

Always provide a clear message in the response body to help clients understand the conflict.

Use 409 Conflict to keep data consistent and avoid overwriting important changes.

Summary

409 Conflict means the request cannot be completed due to a conflict with current server data.

It is useful when multiple clients try to change the same data at once.

Always explain the conflict clearly in the response body.