Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose Python class functions as REST services

Tags:

python

rest

So I have a Python library that contains a pile of super useful functions. I would like to be able to call the functions of this lib over a RESTful interface to make the functions available to any language, application or process that supports sockets and wishes to use them.

I don't want to have to code each function individually as a RESTful passthrough as there are hundreds available and they are all subject to change. Is there a standards compliant way to expose these functions to be accessed over REST?

Many thanks for any ideas, project links or advice anyone can give :)

FR

like image 756
FiniteRed Avatar asked Jul 08 '26 21:07

FiniteRed


2 Answers

What I proposed in the comment under your question was pretty much that:


main.py

from flask import Flask
from flask import request

import functions

app = Flask(__name__)


@app.route('/call/<function_name>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def call_function(function_name: str):
    function_to_call = getattr(functions, function_name)
    body = request.json
    return function_to_call(body)


app.run(host="0.0.0.0")

functions.py

def hello_world():
    return "Hello world!"


def hello_name(params: dict):
    name = params["name"]
    return "Hello " + name

Requests examples:

  • GET

http://localhost:5000/call/hello_world

  • POST

http://localhost:5000/call/hello_name

{
  "name": "Tom"
}
like image 158
tkint Avatar answered Jul 11 '26 13:07

tkint


I am doing this exact same thing right now for a number of random devops tools we have. It's not going to be the golden standard of RESTful endpoint work, but sometimes you just need something quick and dirty. Here's what I did:

  1. Build a simple Flask application. Here's a good guide to get you started
  2. For your particular use case, you would create a single REST endpoint, and point that at your script. Use the 'GET' HTTP request type so you can use URL params.
  3. From there, you can pass parameters on the URL. So if your script takes in 3 arguments, add the following after your url '?foo=1&bar=2&blarg=3'

Hope this helps.

like image 38
Steve G Avatar answered Jul 11 '26 13:07

Steve G