Skip to content

Instantly share code, notes, and snippets.

@the-teacher
Created August 2, 2023 11:54
Show Gist options
  • Save the-teacher/124d3a667eb7bc0b6f9357bed94b4e54 to your computer and use it in GitHub Desktop.
Save the-teacher/124d3a667eb7bc0b6f9357bed94b4e54 to your computer and use it in GitHub Desktop.
@Cleopatric
Copy link

import requests

BASE_URL = r'https://rickandmortyapi.com/api/character'


class MovieService:
    resp_data = {}

    def __init__(self, url: str):
        self.url = url
        self.session = requests.session()

    def __set_resp_data(self, resp):
        if resp and resp.status_code == 200:
            self.resp_data = resp.json()
            return resp.json()

    def __fetch(self):
        try:
            resp = self.session.get(self.url)
            return resp
        except requests.exceptions.ConnectionError as error:
            print(str(error))

    def fetch(self) -> dict:
        self.resp_data.clear()
        resp = self.__fetch()
        self.__set_resp_data(resp)
        return {}

    def print_data(self, items_count: int) -> None:
        data = self.resp_data.get('results', [])
        if len(data) >= items_count:
            for item in data[0:items_count + 1]:
                print(item.get('name', ''))


if __name__ == '__main__':
    service = MovieService(BASE_URL)
    service.fetch()
    service.print_data(2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment