How to call an internal Python service for a Java-based Spring Boot project

3.9k views Asked by At

I have the following problem and I am asking for the better approach.

I have to execute a Python script from the inside of a Spring Boot project. The script should be pretty easy but was made by other people and if possible I want to avoid the needing of change it.

From what I have understand I have two options:

  1. From my Java code I execute a shell command, something like shown here: https://www.baeldung.com/run-shell-command-in-java

Using this approach probably I have to handle the operating system recognition of where my script run and deal with it.

  1. Using Jython to embedd Python code into my Java code but I really don't know how it works and if probably I will face compatibility code (the code was made from other people, it should be very easy but it is better if I have not to change something on this code).

So what way you suggest me?

1

There are 1 answers

0
yahyatoraman On

A better approach would be to treat the Python script as an external service to be called rather than a file to be executed. In this case, I would strongly advise Flask as a light-weight framework.

A simple flask application would look something like this:

from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/')
def hello():
    # Call your script method here
    return jsonify(success=True)

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

In the case of local development, you can run this application with the shell command "python filename.py". By default, you can call this service by http://127.0.0.1:5000/ using the preferred Java method of yours.