Skip to content

To create a **UUID server #4

@MiladGharacheh

Description

@MiladGharacheh

Full Python Code for UUID Server

from flask import Flask, jsonify
import uuid

app = Flask(__name__)

@app.route("/generate", methods=["GET"])
def generate_uuid():
    """
    Generates a random UUID and returns it as JSON.
    """
    uuid_str = str(uuid.uuid4())
    return jsonify({"uuid": uuid_str})

@app.route("/generate-many/<int:count>", methods=["GET"])
def generate_many_uuids(count):
    """
    Generates multiple UUIDs and returns them as JSON.
    """
    if count < 1 or count > 100:
        return jsonify({"error": "Invalid count. Must be between 1 and 100."}), 400
    uuids = [str(uuid.uuid4()) for _ in range(count)]
    return jsonify({"uuids": uuids})

@app.route("/", methods=["GET"])
def index():
    """
    Returns a welcome message with instructions.
    """
    return """
    <h1>UUID Generator Server</h1>
    <p>Endpoints:</p>
    <ul>
        <li><b>Generate Single UUID:</b> <code>/generate</code></li>
        <li><b>Generate Multiple UUIDs:</b> <code>/generate-many/&lt;count&gt;</code></li>
    </ul>
    """

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

How It Works

  1. Endpoints:

    • /generate: Generates a single UUID and returns it as JSON.
    • /generate-many/<count>: Generates multiple UUIDs (up to 100) and returns them as JSON.
    • /: Displays a simple HTML page with instructions.
  2. UUID Generation:

    • The uuid.uuid4() function generates a random UUID.
    • Multiple UUIDs are generated using a list comprehension.
  3. Run the Server:

    • The Flask app runs on 0.0.0.0:5000 by default.

Running the Server

  1. Save the code to a file, e.g., uuid_server.py.

  2. Run the server:

    python uuid_server.py
  3. Access the server in your browser or via curl:

    • Single UUID:

      curl http://localhost:5000/generate

      Output:

      {
        "uuid": "f9b8a7c6-d5e4-4f3a-8b2c-1d0e9f8a7b6c"
      }
    • Multiple UUIDs:

      curl http://localhost:5000/generate-many/5

      Output:

      {
        "uuids": [
          "f9b8a7c6-d5e4-4f3a-8b2c-1d0e9f8a7b6c",
          "e5d4c3b2-a1f0-4e9d-8c7b-6a5d4e3f2a1b",
          "d4e3f2a1-b0c9-8d7e-6f5a-4b3c2d1e0f9a",
          "c3b2a1f0-e9d8-7c6b-5a4d-3e2f1a0b9c8d",
          "b2a1c0d9-e8f7-6a5b-4c3d-2e1f0a9b8c7d"
        ]
      }

Notes

  • Limitation: The /generate-many endpoint is limited to a maximum of 100 UUIDs per request to prevent abuse.
  • Deployment: You can deploy this server using Gunicorn, Docker, or any other deployment method.

Let me know if you need help deploying or extending this server!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions