How to communicate between different programming languages?

2.5k Views Asked by At

I have wrote an api for my python code like this:

def greet_in_python(name, greets="Hello"):
    ## in real life this implementation may be more complex and has other **python** dependencies
    ....
    return greets + " " + name

But only python developers can use my api.

What i want to do is the same thing but with a different language, like javascript, and without rewriting the whole code from python. I thought there must be a way for javascript to communicate with this python api, execute it, and get the result so that javascript developers too can use my api.

greet_in_javascript(name, greets) {
    // talk to my python api
    // return the result easily
}

In a general sense how two languages can talk to each other?

1

There are 1 best solutions below

2
On

There are two very popular ways to do this, and probably a million others that I will neglect in my answer.

Pipes:

import sys

This is where your use sys.stdin and sys.stdout to read the inputs for your program with the help of your OS, then output the result. Both of these are file-like objects in Python so you are likely already familiar with how to use them. In js and node you have child processes and exec and so on which can do calls to your program e.g. cat file.txt | python myscript.py

APIs:

import flask, django

With this approach you can use frameworks like flask & django to define endpoints (e.g. example.com/api/my/endpoint) which map to your API in a way that makes sense for your business purpose. API design is too broad for me to delve into in this answer (but there are much better folks than I out in the internet who have written brilliantly about that topic.)

Edit:

Bonus: PubSub

I probably should also mention PubSub, which creates a message system that you can publish to and subscribe to, provided you are using a language that has a client for that PubSub system. For example here are all the clients for redis https://redis.io/clients and here is redis pubsub https://redis.io/topics/pubsub