简体   繁体   中英

Python API first try

I am starting with APIs and Python. This code below works fine.

import requests
import json

def jprint(obj):
    # create a formatted string of the Python JSON object
    text = json.dumps(obj, sort_keys=True, indent=4)
    print(text)

response = requests.get("http://api.open-notify.org/astros.json")
print(response.status_code)
print(response.json())
print()
jprint(response.json())

But I am missing something when I try to do something more reusable for later... How to solve the error?

raise TypeError(f'Object of type {o. class . name } ' TypeError: Object of type DataFeed is not JSON serializable

Thank you for help.

import requests
import json

"""Open APIs From Space: https://www.dataquest.io/blog/python-api-tutorial/
"""

class DataFeed:

    base_url = "http://api.open-notify.org/"
    number_of_people_in_space = "astros.json"

    def __init__(self):
        pass

    def _build_url(self):
        url = f"{self.base_url}" \
              f"{self.number_of_people_in_space}"
        return url

    def get(self, url):
        response = requests.get(url)
        content = response.json()
        print(url)
        print(response.status_code)
        print(response.json())

    def get_data_feed(self):
        url = self._build_url()
        self.get(url)

    def jprint(obj):
        # create a formatted string of the Python JSON object
        text = json.dumps(obj, sort_keys=True, indent=4)
        print(text)

message = DataFeed()
message.get_data_feed()
message.jprint()

Don't forget any first argument passed to a class method always refers to itself self .

So when you passed obj , to json.dumps(obj, ...), it passes the instance of DataFeed to json.dumps function. What you want is to pass the response.json() .

class DataFeed:

    base_url = "http://api.open-notify.org/"
    number_of_people_in_space = "astros.json"

    def __init__(self):
        pass

    def _build_url(self):
        url = f"{self.base_url}" \
              f"{self.number_of_people_in_space}"
        return url

    def get(self, url):
        response = requests.get(url)
        self.content = response.json()  #changes made here
        print(url)
        print(response.status_code)
        print(response.json())

    def get_data_feed(self):
        url = self._build_url()
        self.get(url)

    def jprint(self): #changes made here

        # create a formatted string of the Python JSON object
        text = json.dumps(self.content, sort_keys=True, indent=4) #changes made here
        print(text)

message = DataFeed()
message.get_data_feed()
message.jprint()

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