appraisal-rb Logo by Aboling0, CC BY-SA 4.0 kettle-rb Logo by Aboling0, CC BY-SA 4.0 floss-funding Logo by Aboling0, CC BY-SA 4.0 galtzo-floss Logo by Aboling0, CC BY-SA 4.0 omniauth Logo by (presumed) tomeara, (presumed) MIT resque Logo by Resque development team, MIT rubocop-lts Logo by Aboling0, CC BY-SA 4.0 oauth Logo by Chris Messina, CC BY-SA 3.0 ruby-openid Logo by Aboling0, CC BY-SA 4.0

Building RESTful APIs with Python Flask

Flask is a lightweight Python web framework perfect for building RESTful APIs. In this tutorial, we’ll create a simple API.

Why Flask?

Flask is minimalist and flexible, making it ideal for:

Setting Up

First, install Flask:

pip install flask

Creating a Simple API

Here’s a basic Flask API:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api/users', methods=['GET'])
def get_users():
    users = [
        {'id': 1, 'name': 'Alice'},
        {'id': 2, 'name': 'Bob'}
    ]
    return jsonify(users)

@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    # Fetch user from database
    user = {'id': user_id, 'name': 'User ' + str(user_id)}
    return jsonify(user)

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

Running the API

Run your Flask application:

python app.py

Your API is now available at http://localhost:5000/api/users.

Best Practices

Flask makes API development simple and enjoyable!