Monday 16 October 2023

Building a Flask Web API Deployed in Apache to Capture User Information

Flask is a Python web framework that is simple to use and ideal for creating web APIs. Apache is a highly customizable web server that can run your Flask app securely. This blog post will guide you through creating a Flask web API that captures and returns information it can see about the user and deploying it using Apache.

Step 1: Setting Up the Flask App

First, let's create a simple Flask app that will capture and display user information.


from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET'])
def getUserInfo():
    userInfo = {
        "remoteAddr": request.remote_addr,
        "userAgent": request.headers.get("User-Agent"),
        "acceptLanguage": request.headers.get("Accept-Language")
    }
    return userInfo

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

Step 2: Test Locally

Run your Flask app and navigate to http://localhost:5000 in your web browser. You should see a JSON object containing information like your IP address, User-Agent, and accepted languages.

Step 3: Prepare for Apache Deployment

  1. Save the Flask app in a folder called MyFlaskApp.
  2. Inside MyFlaskApp, create a file called myFlaskApp.wsgi:

import sys
sys.path.insert(0, '/path/to/MyFlaskApp')
from yourFlaskFileName import app as application
    

Replace /path/to/MyFlaskApp and yourFlaskFileName with appropriate values.

Step 4: Apache Configuration

Open the Apache configuration file (httpd.conf or a site-specific configuration file).

  1. Make sure the following lines are uncommented:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
    
  1. Add the following ProxyPass configuration:

<VirtualHost *:80>
    ServerName yourDomainOrIP

    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/

    WSGIDaemonProcess MyFlaskApp threads=5
    WSGIScriptAlias / /path/to/MyFlaskApp/myFlaskApp.wsgi

    <Directory /path/to/MyFlaskApp>
        WSGIProcessGroup MyFlaskApp
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>
</VirtualHost>
    

Replace yourDomainOrIP and /path/to/MyFlaskApp with appropriate values.

Step 5: Restart Apache

Restart Apache to apply the changes.


sudo systemctl restart apache2  # For Ubuntu
sudo apachectl restart  # For macOS and other UNIX
    

You've successfully created a Flask web API that captures user information and deployed it using Apache. Now when you navigate to http://yourDomainOrIP, you will see the same user information as before, but served through Apache.

No comments:

Post a Comment