Home > Mobile >  TypeError: Object of type Response is not JSON serializable
TypeError: Object of type Response is not JSON serializable

Time:11-03

I am trying to use Python and APIs to build an SQL table with the names of the first 100 Pokemon in the Poke API. Here's my code

import psycopg2, json, requests, hidden

# Load secrets
secrets = hidden.secrets()

conn = psycopg2.connect(host=secrets['host'],
        port=secrets['port'],
        database=secrets['database'],
        ...,
        connect_timeout=3)

cur = conn.cursor()

defaulturl = 'https://pokeapi.co/api/v2/pokemon?limit=100&offset=0'


sql = '''
CREATE TABLE IF NOT EXISTS pokeapi
(id SERIAL, body JSONB); 
'''

cur.execute(sql)

response = requests.get(defaulturl)
js = response.json() 


results = js['results'] 



for x in range(len(results)):
    body = requests.get(results[x]['url'])
    js_body = json.dumps(body) 
    sql = f"INSERT INTO pokeapi (body) VALUES ('{js_body}'::JSONB)";
    cur.execute(sql, (defaulturl))

print('Closing database connection...')
conn.commit()
cur.close() 

And the error is coming up for this line

---> 35 js_body = json.dumps(body)

I'm not sure what's causing the error.

CodePudding user response:

requests.get() returns the entire response, not just the body text.

If you want the body text, use the text attribute of the response object:

response = requests.get(results[x]['url'])
js_body = json.dumps(response.text)
  • Related