1
8 Comments

How to convert Python to API?

I have a Python script that takes in financial data and does some computation. I run it off my Linux server in a virtualenv. I did a hack to make it "like an API" by using PHP to wrap it and calling the Python scripts via exec_command() and echo-ing the output, so that I can have something like an API end-point.

This works but the performance sucks. How can I make this into a proper API?

Thanks for any help or advice!

on February 2, 2021
  1. 1

    As per the other answers, Flask is a nice way to web-enable Python. Furthermore, I use the Flask extension flask-restx to help with the API - advantages include auto-generating Swagger documentation for your API. Note that flask-restx is still actively maintained, whereas the earlier flask-restful and flask-restplus aren't.

  2. 1

    why do flask examples like to take port 5000 to serve requests and not use the common http/s ports like 8080 or 80? is there any reason?
    also, creating an api endpoint but needing to specify a different port looks weird in terms of usage, even though it still works.

    1. 1

      Ports under 1024 are restricted by linux based OSs by default. You can use them if you use privileged access, but this may hide issues in development environments.

      Flask as a server (default port 5000) is not meant as a production environment. The correct setup is using a WSGI process to run it (i.e unicorn, uwsgi, etc’) and connecting to a reverse proxy which handles port 80/443 for you (i.e nginx).

      Good luck!

  3. 1

    Should be pretty straightforward with Flask, check this minimal app. Put your logic and create an endpoint to call the function.

    For deployment, you can check this tutorial on digitalocean.

  4. 1

    thank you so much for everyone's help!

  5. 1

    That does indeed depend on how you want your API to be consumed.

    If it's locally, i.e. by some team mates of yours, then build a package / wheel out of your code and pass this to them.

    If you want to provide public access to your API we some webserver, Flask is indeed a fine option. You might also want to consider FastAPI.

  6. 1

    Look at Python Flask and Waitress that allows you set up a webservice endpoint

  7. 1

    View some tutorials on Python Flask and also deploying Flask to something like PythonAnywhere or Heroku