APIs עם requestsAPIs with requests
HTTP, GET, קודי סטטוס, JSON מהרשת וטיפול בשגיאות רשת.
HTTP, GET, status codes, JSON from the web and handling network errors.
01מה זה API?What is an API?
כשאתם פותחים אתר, הדפדפן שולח בקשת HTTP ומקבל דף. API עובד אותו דבר, רק שהתשובה מיועדת לתוכנות: נתונים נקיים ב-JSON. ספריית requests (התקנתם במפגש 13) שולחת את הבקשה. כאן נשתמש ב-Open Library, ספרייה פתוחה עם API חינמי. שימו לב: הקוד באתר רץ בזמן הבנייה בלי אינטרנט, ולכן תשובות השרת כאן הוקלטו מראש. על המחשב שלכם תקבלו תשובה חיה.
When you open a site, the browser sends an HTTP request and gets a page. An API works the same, except the reply is for programs: clean data in JSON. The requests library (installed in session 13) sends the request. Here we use Open Library, an open library with a free API. Note: the code on this site runs at build time without internet, so the server replies here were recorded in advance. On your computer you'll get a live reply.
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"])200 application/json Dune 604
API הוא כמו חלון הזמנות במסעדה: לא נכנסים למטבח. מוסרים הזמנה בפורמט שהם מבינים, ומקבלים מנה מוכנה.
An API is like a restaurant's order window: you don't walk into the kitchen. You hand in an order in the format they understand, and get a finished dish.
שוכחים להתקין את requests בסביבה הפעילה.
Forgetting to install requests in the active environment.
import requests_html_typoTraceback (most recent call last):
File "/Users/you/python-course/first_api.py", line 1, in <module>
import requests_html_typo
ModuleNotFoundError: No module named 'requests_html_typo'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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02קודי סטטוסStatus codes
לא כל בקשה מצליחה. קוד הסטטוס אומר מה קרה: 2xx הצלחה, 4xx בעיה בבקשה שלנו (כמו ISBN שלא קיים), 5xx תקלה בשרת. בודקים r.ok או קוראים ל-r.raise_for_status(), שזורקת חריגה ברורה כשמשהו נכשל, במקום להמשיך עם נתונים שגויים.
Not every request succeeds. The status code says what happened: 2xx success, 4xx a problem with our request (like an ISBN that doesn't exist), 5xx a server fault. Check r.ok or call r.raise_for_status(), which raises a clear exception when something failed, instead of carrying on with bad data.
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:
print(isbn, "→", r.status_code, r.reason)9780441172719 → Dune 0000000000 → 404 Not Found
| קודCode | משמעותMeaning | מה עושיםWhat to do |
|---|---|---|
| 200 | הצליחOK | קוראים את הגוףRead the body |
| 201 | נוצרCreated | אחרי POSTAfter a POST |
| 400 | בקשה שגויהBad request | בודקים פרמטריםCheck parameters |
| 401 / 403 | אין הרשאהNot allowed | מפתח API?API key? |
| 404 | לא נמצאNot found | כתובת או מזהה שגוייםWrong address or id |
| 429 | יותר מדי בקשותToo many requests | מאטיםSlow down |
| 500 | תקלה בשרתServer error | מנסים שוב אחר כךTry again later |
קוד סטטוס הוא כמו הצליל של כספומט: צליל אחד "הכול טוב", צליל אחר "הכרטיס לא תקין", ואחר "המכשיר מקולקל".
A status code is like an ATM's beep: one beep "all good", another "card invalid", another "machine broken".
קוראים JSON מתשובה שנכשלה.
Reading JSON from a failed reply.
import requests
r = requests.get("https://openlibrary.org/isbn/0000000000.json", timeout=10)
r.raise_for_status()
print(r.json()["title"])Traceback (most recent call last):
File "/Users/you/python-course/status.py", line 3, in <module>
r.raise_for_status()
~~~~~~~~~~~~~~~~~~^^
File "/usr/local/lib/python3.13/site-packages/requests/models.py", line 1167, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://openlibrary.org/isbn/0000000000.jsonrequests.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.ממפים קודי סטטוס להסבר, בלי רשת.
Map status codes to meanings, no network needed.
MEANING = {200: "OK", 404: "Not found", 500: "Server error"}
for code in [200, 404, 418]:
print(code, MEANING.get(code, "Unknown"))200 OK 404 Not found 418 Unknown
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03פרמטרים בכתובתQuery parameters
לחיפוש מעבירים פרמטרים: ?q=dune. אל תבנו את המחרוזת ביד: רווחים, עברית וסימנים כמו & צריכים קידוד. מעבירים מילון ב-params, ו-requests מטפל בכל השאר. r.url מראה את הכתובת שנשלחה בפועל.
To search you pass query parameters: ?q=dune. Don't build the string by hand: spaces, Hebrew and symbols like & need encoding. Pass a dict in params, and requests handles the rest. r.url shows the address actually sent.
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"]:
print(f'{doc["title"]} ({doc["first_publish_year"]})')https://openlibrary.org/search.json?q=frank+herbert&limit=2 2 Dune (1965) Dune Messiah (1969)
params הוא כמו טופס הזמנה עם שדות: במקום לכתוב הכול בשורה אחת ולקוות שיבינו, ממלאים כל שדה במקום שלו.
params is like an order form with fields: instead of writing everything on one line and hoping, you fill each field in its place.
ניגשים למפתח שלא קיים בכל תוצאה.
Accessing a key that isn't in every result.
doc = {"title": "Untitled draft"}
print(doc["first_publish_year"])Traceback (most recent call last):
File "/Users/you/python-course/search.py", line 2, in <module>
print(doc["first_publish_year"])
~~~^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'first_publish_year'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", "?").צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04timeout ותקלות רשתTimeouts and network failures
רשת נופלת, שרתים איטיים, וכתובות משתנות. בלי timeout, התוכנית יכולה לחכות לנצח. עוטפים בקשה ב-try ותופסים requests.exceptions.RequestException, האב של כל שגיאות הרשת, ומחזירים הודעה שהמשתמש מבין.
Networks drop, servers are slow, and addresses change. Without a timeout, a program can wait forever. Wrap a request in try and catch requests.exceptions.RequestException, the parent of every network error, and return a message the user understands.
import requests
def fetch(url):
try:
r = requests.get(url, timeout=3)
r.raise_for_status()
return r.json()
except requests.exceptions.Timeout:
print("השרת לא ענה בזמן:", url)
except requests.exceptions.RequestException as e:
print("תקלת רשת:", type(e).__name__)
return None
print(fetch("https://openlibrary.org/isbn/9780141439587.json")["title"])
print(fetch("https://httpbin.org/delay/10"))
print(fetch("https://httpbin.org/status/500"))
print(fetch("https://openlibrary.example/isbn/1.json"))import requests
def fetch(url):
try:
r = requests.get(url, timeout=3)
r.raise_for_status()
return r.json()
except requests.exceptions.Timeout:
print("the server did not answer in time:", url)
except requests.exceptions.RequestException as e:
print("network problem:", type(e).__name__)
return None
print(fetch("https://openlibrary.org/isbn/9780141439587.json")["title"])
print(fetch("https://httpbin.org/delay/10"))
print(fetch("https://httpbin.org/status/500"))
print(fetch("https://openlibrary.example/isbn/1.json"))Emma השרת לא ענה בזמן: https://httpbin.org/delay/10 None תקלת רשת: HTTPError None תקלת רשת: ConnectionError None
Emma the server did not answer in time: https://httpbin.org/delay/10 None network problem: HTTPError None network problem: ConnectionError None
timeout הוא כמו לחכות לחבר בבית קפה: אחרי חצי שעה מתקשרים או הולכים, ולא יושבים שם עד הסגירה.
A timeout is like waiting for a friend at a café: after half an hour you call or leave, rather than sitting there until closing.
כתובת שגויה בלי try: התוכנית קורסת עם הודעה ארוכה ומפחידה.
A wrong address without try: the program crashes with a long scary message.
import requests
requests.get("https://openlibrary.example/isbn/1.json", timeout=5)Traceback (most recent call last):
File "/Users/you/python-course/safe_fetch.py", line 2, in <module>
requests.get("https://openlibrary.example/isbn/1.json", timeout=5)
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/requests/api.py", line 87, in get
return request("get", url, params=params, **kwargs)
File "/usr/local/lib/python3.13/site-packages/requests/api.py", line 71, in request
return session.request(method=method, url=url, **kwargs)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/requests/sessions.py", line 651, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.13/site-packages/requests/sessions.py", line 784, in send
r = adapter.send(request, **kwargs)
File "/Users/you/sc/sitecustomize.py", line 23, in _send
raise requests.exceptions.ConnectionError(
f"HTTPSConnectionPool(host='{host}', port=443): Max retries exceeded with url: {urlsplit(url).path} "
f"(Caused by NameResolutionError(\"Failed to resolve '{host}'\"))", request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='openlibrary.example', port=443): Max retries exceeded with url: /isbn/1.json (Caused by NameResolutionError("Failed to resolve 'openlibrary.example'"))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.05לשלוח נתונים: POSTSending data: POST
GET מביא נתונים. POST שולח נתונים לשרת, למשל ביקורת חדשה. json= הופך מילון ל-JSON ושולח אותו. API שדורש הרשאה מקבל מפתח בכותרת (headers); את המפתח שומרים במשתנה סביבה, לא בקוד (זוכרים את .gitignore?). httpbin.org הוא שירות בדיקה שמחזיר את מה ששלחתם:
GET fetches data. POST sends data to the server, say a new review. json= turns a dict into JSON and sends it. An API that needs permission receives a key in a header (headers); keep the key in an environment variable, not in code (remember .gitignore?). httpbin.org is a test service that echoes what you sent:
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)
print(r.json()["json"])200
{'title': 'Dune', 'stars': 5, 'text': 'Sand everywhere, loved it'}GET הוא כמו לשאול ספרנית "יש לכם את דיונה?", ו-POST הוא כמו למסור לה טופס המלצה שיתויק.
GET is like asking the librarian "do you have Dune?", and POST is like handing her a recommendation form to file.
שולחים data= כשהשרת מצפה ל-JSON.
Sending data= when the server expects JSON.
import requests
r = requests.post("https://httpbin.org/post", data={"stars": 5}, timeout=10)
assert r.json()["json"] == {"stars": 5}, f"server got {r.json()['json']!r}: data= sends a form, json= sends JSON"Traceback (most recent call last):
File "/Users/you/python-course/post.py", line 3, in <module>
assert r.json()["json"] == {"stars": 5}, f"server got {r.json()['json']!r}: data= sends a form, json= sends JSON"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: server got 'stars=5': data= sends a form, json= sends JSONAssertionError: 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=.06להפריד הבאה מעיבודSeparate fetching from processing
טריק של מקצוענים: הפונקציה שמדברת עם הרשת קטנה ככל האפשר, וכל העיבוד (בחירת שדות, ניקוי, חישוב) בפונקציה נפרדת שמקבלת מילון רגיל. כך אפשר לבדוק את העיבוד עם pytest בלי אינטרנט, ובאתר הזה, כל תרגילי המפגש עובדים כך. ומטמון (cache) קטן חוסך בקשות חוזרות.
A pro trick: the function that talks to the network is as small as possible, and all processing (picking fields, cleaning, computing) lives in a separate function that takes a plain dict. That way you can test processing with pytest without internet, and on this site, every exercise in this session works that way. A small cache saves repeat requests.
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,
}
recorded = {'title': 'Dune', 'authors': [{'key': '/authors/OL79034A'}], 'number_of_pages': 604, 'publishers': ['Ace'], 'publish_date': '1990'}
print(to_book(recorded, "Frank Herbert"))
print(to_book({"title": " Untitled "})){'title': 'Dune', 'author': 'Frank Herbert', 'pages': 604, 'year': 1990}
{'title': 'Untitled', 'author': '?', 'pages': 0, 'year': None}צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
להפריד הבאה מעיבוד זה כמו להפריד בין קניות לבישול: אפשר לתרגל בישול עם מצרכים שכבר בבית, בלי לרוץ לסופר בכל פעם.
Separating fetching from processing is like separating shopping from cooking: you can practise cooking with ingredients already at home, without running to the store each time.
משתמשים ב-r.text (מחרוזת) כאילו היה מילון.
Using r.text (a string) as if it were a dict.
import requests
r = requests.get("https://openlibrary.org/isbn/9780441172719.json", timeout=10)
print(r.text["title"])Traceback (most recent call last):
File "/Users/you/python-course/process.py", line 3, in <module>
print(r.text["title"])
~~~~~~^^^^^^^^^
TypeError: string indices must be integers, not 'str'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.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.