My First REST API with Python and Flask-RESTPlus

With few or no explanations, on Debian 10:

sudo apt install nginx python3-venv curl
cd
mkdir resttest
cd resttest
python3 -m venv venv
. venv/bin/activate
pip install wheel
pip install flask flask-restplus gunicorn
deactivate

The actual API app, in ~/resttest/resttest.py:

from flask import Flask
from flask_restplus import Api, Resource

app = Flask(__name__)
api = Api(app)

@api.route("/test/<int:id>")
class Test(Resource):
    def get(self, id):
        return {"result":"get {} ok".format(id)}, 200

# For testing without the external runner:
if __name__ == "__main__":
    app.run(host="0.0.0.0")

~/resttest/wsgi.py:

from resttest import app

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

/etc/systemd/system/resttest.service:

[Unit]
Description=My REST test app, run by Gunicorn
After=network.target

[Service]
User=markku
Group=www-data
WorkingDirectory=/home/markku/resttest
Environment="PATH=/home/markku/resttest/venv/bin"
ExecStart=/home/markku/resttest/venv/bin/gunicorn --workers 3 --bind unix:resttest.sock --umask 007 wsgi:app

[Install]
WantedBy=multi-user.target

/etc/nginx/sites-available/resttest:

server {
    listen 80;
    server_name my.server.name;
    location / {
        include proxy_params;
        proxy_pass http://unix:/home/markku/resttest/resttest.sock;
    }
}

Final setup steps:

sudo ln -s /etc/nginx/sites-available/resttest /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl start resttest
sudo systemctl enable resttest
sudo systemctl restart nginx

Testing results:

$ curl http://my.server.name/test/555
{"result": "get 555 ok"}

Also note that the Swagger UI is automatically accessible in http://my.server.name/:

Some future considerations:

  • TLS encryption (= reconfiguring NGINX)
  • Authentication for the API
  • Disabling/customizing the Swagger UI

Links:

The post was inspired by: How To Serve Flask Applications with Gunicorn and Nginx on Ubuntu 18.04 (digitalocean.com)

Updated: October 12, 2019 — 18:11

Leave a Reply