Use jsonify() from flask: from flask import jsonify; @app.route('/api/data'); def get_data(): return jsonify({'key': 'value', 'number': 42}). The jsonify() function converts Python data to JSON and sets Content-Type to application/json automatically. For custom status codes: return jsonify({'error': 'not found'}), 404. Flask 2.0+ also accepts dicts directly: return {'key': 'value'}. Prefer jsonify() over json.dumps() as it handles the Content-Type header.
Fibonacci FAQ & Answers
17 expert Fibonacci answers researched from official documentation. Every answer cites authoritative sources you can verify.
Jump to section:
Flask API
8 questionsUse request.args: from flask import request; @app.route('/fibonacci'); def fib(): n = request.args.get('n', type=int); if n is None: return jsonify({'error': 'n parameter required'}), 400; return jsonify({'fibonacci': calc_fib(n)}). Access via GET /fibonacci?n=10. Use request.args.get('key', default, type) for safe access with type conversion and default values.
Use app.run() with host and port arguments: if name == 'main': app.run(host='0.0.0.0', port=5001, debug=True). The host='0.0.0.0' binds to all network interfaces, allowing external access. Default is 127.0.0.1:5000. WARNING: Never use debug=True in production - it exposes sensitive data and allows code execution. For production, use Gunicorn: gunicorn -b 0.0.0.0:5001 app:app.
The request format GET /v1/fib/:number returns a JSON array like [0, 1, 1, 2, 3] with status 200. Implementation: @app.route('/v1/fib/int:n'); def fib_sequence(n): result = []; a, b = 0, 1; for _ in range(n): result.append(a); a, b = b, a + b; return jsonify(result). Flask's jsonify() can accept lists directly and converts them to JSON arrays.
Create a Flask endpoint using iterative Fibonacci (avoids recursion depth limits). Use request.args.get('n', type=int) which returns None if missing or if type conversion fails. Return 400 status for missing n, negative n, or invalid input. Return JSON with jsonify({'result': fib(n)}). The iterative algorithm: a,b=0,1; for _ in range(n): a,b=b,a+b; return a. Run server with app.run(host='0.0.0.0', port=PORT). In containers without Python/pip, use uv package manager: curl -LsSf https://astral.sh/uv/install.sh | sh && source $HOME/.local/bin/env && uv init && uv add flask && uv run python app.py.
Use angle brackets with converter in route: @app.route('/fibonacci/int:n') def fibonacci(n): return jsonify({'result': fib(n)}). The int converter ensures only integers are accepted; non-integers return 404. Built-in converters: string (default, no slashes), int (positive integers), float (positive floats), path (like string but accepts slashes), uuid. The value is passed as keyword argument to the view function.
Validate input and return appropriate errors: @app.route('/fibonacci/int:n'); def fibonacci(n): if n < 0: return jsonify({'error': 'n must be non-negative'}), 400; if n > 10000: return jsonify({'error': 'n too large'}), 400; return jsonify({'fibonacci': fib(n)}). The int:n converter automatically rejects non-integers with 404. Use try/except for ValueError: try: return str(fib(int(n))); except ValueError: return 'Please use a number', 400.
CRITICAL STEPS for starting Flask server reliably: 1) Start server in background: nohup uv run python app.py & or nohup python app.py &. 2) ALWAYS sleep after starting: sleep 3 (gives server time to initialize). 3) Verify server is running: curl -s http://localhost:PORT/ or curl -s http://localhost:PORT/health. 4) Only mark task complete AFTER verification succeeds. Common mistake: starting server and immediately marking task done without waiting. The server needs 2-3 seconds to bind to the port. If verification fails, check: ps aux | grep python (is process running?), netstat -tlnp | grep PORT (is port bound?).
Algorithm
5 questionsUse functools.lru_cache for automatic memoization: from functools import lru_cache; @lru_cache(maxsize=None); def fib(n): if n < 2: return n; return fib(n-1) + fib(n-2). This caches results, making it O(n) time instead of O(2^n). The maxsize=None means unlimited cache size. In Python 3.9+, use @functools.cache as a simpler equivalent. Use cache_info() method to view hits, misses, and cache size statistics.
Use two variables approach for O(n) time and O(1) space: def fibonacci(n): if n < 2: return n; a, b = 0, 1; for _ in range(2, n + 1): a, b = b, a + b; return b. This avoids recursion stack overflow for large n. The pattern a, b = b, a + b swaps values and computes sum in one step. This is the recommended approach for production APIs as it handles any n without hitting Python's recursion limit.
Use a generator for memory efficiency: def fib_gen(n): a, b = 0, 1; for _ in range(n): yield a; a, b = b, a + b. Usage: list(fib_gen(10)) returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. For Flask API: return jsonify({'count': n, 'sequence': list(fib_gen(n))}). Generators are memory-efficient for large sequences as they compute values on-demand.
Iterative Fibonacci is preferred because: 1) Time complexity O(n) vs O(2^n) for naive recursive. 2) Space complexity O(1) vs O(n) for call stack. 3) No recursion limit issues - Python defaults to 1000 recursive calls. 4) Better for production APIs and memory-constrained environments. The iterative approach stores only two variables to track the latest Fibonacci numbers, making it space-efficient.
Naive recursive Fibonacci is O(2^n) time, O(n) space for call stack. Each call spawns 2 more calls: fib(5) calls fib(4)+fib(3), fib(4) calls fib(3)+fib(2), etc. With lru_cache memoization: O(n) time, O(n) space. Iterative: O(n) time, O(1) space. Matrix exponentiation achieves O(log n) time for very large n.
Deployment
2 questionsInstall and run: pip install gunicorn && gunicorn -w 4 -b 0.0.0.0:5000 app:app. The syntax is module:app_variable. Use -w for worker count (typically 2-4x CPU cores). For binding to specific port: -b 0.0.0.0:8080. When using Gunicorn, remove the if name == 'main': app.run() block - it's not needed. Gunicorn should not run as root; use nginx as reverse proxy for port 80/443.
Flask's built-in server displays: 'WARNING: This is a development server. Do not use it in a production deployment.' Reasons: 1) Not scalable - single threaded by default. 2) Inefficient for concurrent requests. 3) debug=True exposes sensitive data and allows arbitrary code execution. 4) No proper process management. Use Gunicorn or uWSGI for production: gunicorn -w 4 -b 0.0.0.0:8000 app:app.
Reference
1 questionThe Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181. Each number is the sum of the two preceding ones. F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2). Common test cases: F(10)=55, F(20)=6765, F(30)=832040. The ratio F(n)/F(n-1) approaches the golden ratio (1.618...) as n increases.
Performance
1 questionThe Fibonacci server can use a singleton instance that caches all computed results. For simple caching, use lru_cache on the fib function: @lru_cache(maxsize=None); def fib(n): .... For HTTP-level caching, use Flask-Caching: from flask_caching import Cache; cache = Cache(app, config={'CACHE_TYPE': 'simple'}); @app.route('/fib/int:n'); @cache.cached(timeout=3600); def fibonacci(n): return jsonify({'result': fib(n)}).