JustCaptain kod-buduschego
4abf428db282a82f6419bf2c3d8b27580eeca244
Перейти к файлу
Код
kod-buduschego Python 2025-20263.9. Методы APIexamplemain.py
anc update c70a58f 8 октября 2026 г.
main.py
from typing import Any
import requests
import json

url_posts: str = "https://jsonplaceholder.typicode.com"


class PostAPI:
    def __init__(self, base_url: str) -> None:
        self.base_url: str = base_url

    def _get_request(self, url: str) -> Any:
        response = requests.get(url=url)
        data = response.json()
        return data

    def _post_request(self, url: str, data: dict) -> Any:
        response = requests.post(url=url, data=data)
        raw = response.json()
        return raw

    def get_posts(self, write=False) -> list[dict]:
        data = self._get_request(url=f"{self.base_url}/posts")
        if write:
            with open(file="data.json", mode="w", encoding="utf-8") as file:
                json.dump(obj=data, fp=file, indent=4)
        return data

    def get_post(self, post_id: int, write_path=None) -> list[dict]:
        data = self._get_request(url=f"{self.base_url}/posts/{post_id}")
        if write_path:
            with open(file=write_path, mode="w", encoding="utf-8") as file:
                json.dump(obj=data, fp=file, indent=4)
        return data

    def create_post(self, title: str, body: str, user_id: int) -> dict:
        data = {"title": title, "body": body, "userId": user_id}
        raw = self._post_request(url=f"{self.base_url}/posts", data=data)
        return raw


def get_jokes() -> None:
    url = "https://geek-jokes.sameerkumar.website/api?format=json"
    response = requests.get(url=url)
    print(response.text)


print("Hello world")

post_api = PostAPI(base_url=url_posts)
# print(post_api.get_posts(write=True))
# print(post_api.get_post(post_id=5, write_path="post.json"))
"""
print(
    post_api.create_post(
        title="купить марковку", body="Ой какой то там body", user_id=5
    )
)
"""
get_jokes()