נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
22
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

APIs עם requestsAPIs with requests

HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.

HTTP, GET, status codes, JSON from the web and handling network errors.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • דף לבני אדם, API לתוכנותPages for people, APIs for programs
  • בקשה → תשובה עם קוד וגוףRequest → reply with a code and a body
  • 200 הצליח, 404 לא נמצא, 500 תקלה אצלם200 OK, 404 not found, 500 their problem
  • r.ok = True לכל 2xxr.ok = True for any 2xx
  • params={"q": "dune"} במקום לבנות מחרוזתparams={"q": "dune"} instead of building a string
  • requests מקודד רווחים ותווים מיוחדיםrequests encodes spaces and special characters
  • תמיד timeout=Always timeout=
  • requests.exceptions.RequestException תופסת הכולrequests.exceptions.RequestException catches them all
  • GET מבקש, POST שולחGET asks, POST sends

מונחיםTerms

  • APIAPI: ממשק שתוכנה אחת חושפת לאחרות. ב-API של אתר שולחים בקשה לכתובת ומקבלים נתונים (לרוב JSON) במקום דף.An interface one program exposes to others. With a web API you send a request to an address and get data (usually JSON) instead of a page.
  • HTTPHTTP: השפה שבה דפדפנים ותוכנות מדברים עם שרתים: בקשה (GET, POST...) ותשובה עם קוד סטטוס וגוף.The language browsers and programs use to talk to servers: a request (GET, POST...) and a reply with a status code and a body.
  • קוד סטטוסstatus code: מספר בתשובת HTTP: 200 הצליח, 404 לא נמצא, 500 תקלה בשרת. 2xx טוב, 4xx טעות שלנו, 5xx טעות שלהם.A number in an HTTP reply: 200 success, 404 not found, 500 server error. 2xx good, 4xx our mistake, 5xx theirs.
  • נקודת קצה (endpoint)endpoint: כתובת מסוימת ב-API שעונה על סוג אחד של בקשה, למשל /isbn/<מספר>.json.A specific address in an API that answers one kind of request, e.g. /isbn/<number>.json.
  • פרמטרים בכתובתquery parameters: החלק שאחרי ? בכתובת: ?q=dune&limit=2. ב-requests מעבירים אותם כמילון ב-params.The part after ? in a URL: ?q=dune&limit=2. In requests you pass them as a dict in params.
  • timeouttimeout: זמן מקסימלי לחכות לתשובה. בלי timeout, תוכנית יכולה לחכות לנצח לשרת שלא עונה.The longest to wait for a reply. Without one, a program can wait forever for a silent server.

Cheatsheet

APIAPI
import requests

r = requests.get("https://openlibrary.org/isbn/9780441172719.json", timeout=10)
print(r.status_code)
print(r.headers["Content-Type"])
book = r.json()
print(book["title"], book["number_of_pages"])
סטטוסStatus
import requests

for isbn in ["9780441172719", "0000000000"]:
    r = requests.get(f"https://openlibrary.org/isbn/{isbn}.json", timeout=10)
    if r.ok:
        print(isbn, "→", r.json()["title"])
    else:
פרמטריםParams
import requests

r = requests.get("https://openlibrary.org/search.json", params={"q": "frank herbert", "limit": 2}, timeout=10)
print(r.url)
data = r.json()
print(data["numFound"])
for doc in data["docs"]:
תקלותFailures
import requests

def fetch(url):
    try:
        r = requests.get(url, timeout=3)
        r.raise_for_status()
        return r.json()
POSTPOST
import os
import requests

review = {"title": "Dune", "stars": 5, "text": "Sand everywhere, loved it"}
headers = {"Authorization": "Bearer " + os.environ.get("SHELF_API_KEY", "demo")}
r = requests.post("https://httpbin.org/post", json=review, headers=headers, timeout=10)
print(r.status_code)
מבנהStructure
def to_book(data, author="?"):
    return {
        "title": data.get("title", "").strip(),
        "author": author,
        "pages": data.get("number_of_pages", 0),
        "year": int(data["publish_date"][-4:]) if data.get("publish_date") else None,
    }

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do
ModuleNotFoundErrorשוכחים להתקין את requests בסביבה הפעילה.Forgetting to install requests in the active environment.ModuleNotFoundError: No module named 'requests_html_typo': כש-import requests נכשל כך, מפעילים את ה-venv ומריצים pip install requests.ModuleNotFoundError: No module named 'requests_html_typo': when import requests fails like this, activate the venv and run pip install requests.
requests.exceptions.HTTPErrorקוראים JSON מתשובה שנכשלה.Reading JSON from a failed reply.requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://openlibrary.org/isbn/0000000000.json: הספר לא קיים. בלי הבדיקה היינו מקבלים KeyError מבלבל על title.requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://openlibrary.org/isbn/0000000000.json: the book doesn't exist. Without the check we'd get a confusing KeyError on title.
KeyErrorניגשים למפתח שלא קיים בכל תוצאה.Accessing a key that isn't in every result.KeyError: 'first_publish_year': ב-API אמיתי לא לכל רשומה יש כל שדה. משתמשים ב-doc.get("first_publish_year", "?").KeyError: 'first_publish_year': in a real API not every record has every field. Use doc.get("first_publish_year", "?").
requests.exceptions.ConnectionErrorכתובת שגויה בלי try: התוכנית קורסת עם הודעה ארוכה ומפחידה.A wrong address without try: the program crashes with a long scary message.requests.exceptions.ConnectionError: HTTPSConnectionPool(host='openlibrary.example', ...: השם לא קיים או שאין אינטרנט. בודקים את הכתובת, ותופסים את החריגה כדי להציג הודעה ידידותית.requests.exceptions.ConnectionError: HTTPSConnectionPool(host='openlibrary.example', ...: the name doesn't exist or there's no internet. Check the address, and catch the exception to show a friendly message.
AssertionErrorשולחים data= כשהשרת מצפה ל-JSON.Sending data= when the server expects JSON.AssertionError: server got 'stars=5': data= sends a form, json= sends JSON: ל-API של JSON משתמשים ב-json=.AssertionError: server got 'stars=5': data= sends a form, json= sends JSON: for a JSON API use json=.
TypeErrorמשתמשים ב-r.text (מחרוזת) כאילו היה מילון.Using r.text (a string) as if it were a dict.TypeError: string indices must be integers, not 'str': r.text הוא הטקסט הגולמי. r.json() הופך אותו למילון.TypeError: string indices must be integers, not 'str': r.text is the raw text. r.json() turns it into a dict.

נבנה על ידיBuilt by Ariel Yohimovich