Flask App with Random User Retrieval API

  • Share this:

Code introduction


This code defines a Flask application that uses flask_sqlalchemy to manage user data in a SQLite database. It provides an API endpoint that returns information about a random user.


Technology Stack : Flask, Flask-SQLAlchemy, SQLite

Code Type : Flask API

Code Difficulty : Intermediate


                
                    
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import random

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)

# Define a simple model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)

# Function to get a random user
def get_random_user():
    # Query all users
    users = User.query.all()
    # Get a random user if available
    if users:
        return random.choice(users)
    else:
        return None

# JSON response for the API
@app.route('/random_user', methods=['GET'])
def random_user():
    user = get_random_user()
    if user:
        return jsonify({"id": user.id, "name": user.name, "email": user.email})
    else:
        return jsonify({"message": "No users found"}), 404

if __name__ == '__main__':
    db.create_all()  # Create database tables
    app.run(debug=True)