Harry Boy
Harry Boy

Reputation: 4747

How to correctly return a json string from python flask server

I am using a python flask server API to call another python flask server API. Both these have been generated using swagger editor.

API2 returns an encoded string such as:

def Server2_API2():
    payload = {
        "value1": 'somedata',
        "value2": 'somedata',
    }
    encoded_payload = jwt.encode(payload, SECRET, algorithm=ALGORITHM)
    return encoded_payload <-- {str}'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.'

API1 on server 1 calls API2 on server 2 as follows:

def Server1_API1():
    resp = requests.post('http://localhost:1000/API2', data='value1=one&value2=two')
    if resp.status_code == 200:
        first_try = resp.content   <-- b'"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"\n'
        second_try = resp.content.decode() <-- {str} '"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
        '   <- notice the new line here

        return first_try
        #return second_try

If I return first_try then I get the error: Object of type 'bytes' is not JSON serializable

If I return second_try then I get the following data returned:

"\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9\"\n" 

My goal is to have just the data returned as follows without any error or any back slashes or new lines:

e.g. "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"

How can I achieve this?

SOLUTION:

third_try = resp.json() <-- This does the trick :)

Upvotes: 0

Views: 132

Answers (1)

Harry Boy
Harry Boy

Reputation: 4747

This did the trick:

token = resp.json()

Upvotes: 1

Related Questions