Building a Python Flask Service for Automatic ID Generation
This guide demonstrates how to build a Python Flask-based RESTful service that generates various types of unique identifiers—including UUIDs, timestamps, Redis counters, Snowflake IDs, and random strings—while covering installation, code implementation, API endpoints, error handling, rate limiting, and extensibility considerations.
Creating an automatic ID generation service in Python can address many scenarios, such as using UUIDs, timestamps, or database sequences. This article presents a simple yet effective approach using the Flask framework to expose a RESTful API that returns globally unique IDs (UUID) and other ID types.
Installation of dependencies
First, ensure the required Python packages are installed:
pip install flask redis python-decouple simple-snowflakepython-decouple reads configuration from environment variables, and simple-snowflake provides a lightweight Snowflake ID generator.
Flask application code
from flask import Flask, jsonify, request, abort
import uuid
import time
import redis
from decouple import config
from simple_snowflake import SimpleSnowflakeGenerator
import string
import random
from functools import wraps
app = Flask(__name__)
# Initialize Redis client
r = redis.Redis(host=config('REDIS_HOST', default='localhost'), port=config('REDIS_PORT', cast=int, default=6379), db=0)
# Initialize Snowflake generator
snowflake_gen = SimpleSnowflakeGenerator()
# Error handling decorator
def handle_errors(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
return jsonify({"error": str(e)}), 500
return decorated_function
@app.route('/generate_uuid', methods=['GET'])
@handle_errors
def generate_uuid():
new_id = str(uuid.uuid4())
return jsonify({"id": new_id})
@app.route('/generate_timestamp_id', methods=['GET'])
@handle_errors
def generate_timestamp_id():
timestamp_id = str(int(time.time() * 1000))
return jsonify({"id": timestamp_id})
@app.route('/generate_counter_id', methods=['GET'])
@handle_errors
def generate_counter_id():
counter_id = r.incr('counter_id')
return jsonify({"id": counter_id})
@app.route('/generate_snowflake_id', methods=['GET'])
@handle_errors
def generate_snowflake_id():
snowflake_id = snowflake_gen.generate()
return jsonify({"id": snowflake_id})
@app.route('/generate_random_string/', methods=['GET'])
@handle_errors
def generate_random_string(length):
if length <= 0:
abort(400, description="Length must be positive")
letters_and_digits = string.ascii_letters + string.digits
random_str = ''.join(random.choice(letters_and_digits) for _ in range(length))
return jsonify({"id": random_str})
# Simple rate‑limiting middleware (replace with Flask‑Limiter for production)
@app.before_request
def limit_rate():
client_ip = request.remote_addr
key = f"rate_limit:{client_ip}"
if r.exists(key) and int(r.get(key)) >= 10: # max 10 requests per minute
abort(429, description="Too many requests")
else:
pipe = r.pipeline()
pipe.incr(key)
pipe.expire(key, 60) # expire after 60 seconds
pipe.execute()
if __name__ == '__main__':
app.run(debug=True)API endpoints description
/generate_uuid: returns a random UUID v4 according to RFC 4122.
/generate_timestamp_id: returns a string representing milliseconds since the epoch.
/generate_counter_id: uses Redis INCR to produce an incrementing integer ID.
/generate_snowflake_id: generates a near‑unique 64‑bit integer using a Snowflake‑like algorithm.
/generate_random_string/: generates a random alphanumeric string of the length specified in the path parameter.Security and performance optimizations
Error handling: each endpoint is wrapped with a decorator that returns meaningful error messages.
Rate limiting: a simple Redis‑based limiter prevents abuse by restricting requests per minute.
Resource management: proper handling of external resources such as Redis connections, especially in distributed deployments.
Extensibility
The design anticipates future extensions, such as adding more ID types or batch generation capabilities, and uses python-decouple to load configuration from environment variables for easy deployment across environments.
Considerations
Security: in production, add authentication mechanisms like API keys.
Performance: for high concurrency, consider asynchronous frameworks (e.g., FastAPI) or caching frequently used ID types.
Resource management: ensure proper cleanup of external resources.
Scalability: design with future expansion in mind.
Conclusion
By following this approach, you can create a versatile automatic ID generation service that meets diverse application needs, and you can adapt the code to incorporate additional ID generation logic as required.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.