简体   繁体   中英

How to route the client 'GET' request from one API to another another API with same end points using Falcon in python?

I have two APIs with same end points, but different URLs. Like this:

API_1 = /takeout/{t_note}
        /serve/{t_note}/{m_note}

API_2 = /takeout/{t_note}
        /serve/{t_note}/{m_note}

A client send a 'GET' request to API_1 but instead of giving a response back, it just route to API_2 and show the response of API_2, where all the logic happens. Client thinks that it communicate with API_2 but in reality send the request to API_1. So, at the end API_1 is just some proxy, which only route the request to API_2 for response.

Any idea how to achieve this? What i am looking for is this:

class TakeOut(object):
    def on_get (self, resp, req, t_note:str):
        resp.body = json.dumps() # response of API_2 here for endpoint /takeout/{t_note}
                                 # t_note is just a id in string format which sent by the client

Something like this maybe. I am new to falcon and APIs.

app2.py:

import falcon


class Api2(object):
    def on_get(self, _req, resp, arg1: str):
        resp.status = falcon.HTTP_200 if arg1 == '200' else falcon.HTTP_400
        resp.media = {'arg': arg1}


app = falcon.API()
api2 = Api2()
app.add_route('/api2/{arg1}', api2)

app1.py:

import falcon
import requests


class Api1(object):
    def on_get(self, _req, resp, arg1: str):
        api2_resp = requests.get(f'http://127.0.0.1:8000/api2/{arg1}')
        resp.status = falcon.HTTP_200 if api2_resp.status_code == 200 else falcon.HTTP_400
        dic = api2_resp.json()
        dic["api1"] = 'payload'
        resp.media = dic


app = falcon.API()
api1 = Api1()
app.add_route('/api1/{arg1}', api1)

gunicorn app2:app

gunicorn -b '127.0.0.1:8001' app1:app

curl -i http://127.0.0.1:8001/api1/200 => HTTP/1.1 200 OK... {"arg": "200", "api1": "payload"}

curl -i http://127.0.0.1:8001/api1/201 => HTTP/1.1 400 Bad Request... {"arg": "201", "api1": "payload"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM