kampta
kampta

Reputation: 4898

Making REST calls to flask service running on different port

I have two services running in docker-compose, frontend and backend, both developed using flask.

frontend:
  restart: always
  build: ./frontend
  expose:
    - "8000"
  command: /usr/local/bin/gunicorn --bind :8000 run:application

backend:
  restart: always
  build: ./backend
  expose:
    - "9000"
  command: /usr/local/bin/gunicorn --bind :9000 run:application

I am hosting a simple REST API in the backend

@app.route('/api/weather', methods=['GET'])
def get_weather():
    super_cool_function()
    return jsonify({'temperature': 100})

What is the best way to consume this API in frontend? I guess following is one way but I am not sure what should be the input to requests.get()

@app.route('/hello')
def hello():
    r = requests.get()
    return render_template('hello.html', temperature=r.json()['temperature'])

Upvotes: 0

Views: 1416

Answers (1)

Bamcclur
Bamcclur

Reputation: 2029

Without having implemented your setup, I generally make REST calls using requests by implementing a method similar to the following.

def get_weather(data):
    # Set api endpoint to what's needed
    endpoint = 'http://example.com/api/weather:9000'

    # Do any work needed specific to api prior to call

    # Send request and get response
    response = requests.get(url=endpoint, data=data)

    # Process response
    result = process(response)
    return result

You can create a class that is going to make all api calls to the same url, and just change the endpoint.

class ApiCaller():
    def __init__(self, base_url, port):
        self.base_url = base_url
        self.port = port

    def __get_url(self, endpoint):
        return '%s%s%s' % (self.base_url, endpoint, self.port)

    def get_weather(self, data):
        endpoint = 'weather' 
        return requests.get(url=self.__get_url(endpoint), data=data)

    def get_hello(self, data)
        endpoint = 'hello'
        return requests.get(url=self.__get_url(endpoint), data=data)

Upvotes: 1

Related Questions