Practice: Requests Library
Q1. Install the library
Write the terminal command that installs requests.
Goal: Install a package.
Q2. Prepare a URL
Use requests.Request to prepare a GET to https://x.io/s with params {'q': 'cat'} and print the URL.
Goal: Use params.
Q3. Params with two keys
Prepare a GET to https://x.io/list with params {'a': 1, 'b': 'two'} and print the URL.
Goal: Use params.
Q4. Escaped space
What does this print?
import requests
p = requests.Request("GET", "https://x.io/s", params={"q": "a b"}).prepare()
print(p.url)Goal: Understand escaping.
Q5. Prepared headers
What does this print?
import requests
p = requests.Request("GET", "https://x.io", headers={"X-Id": "7"}).prepare()
print(p.headers["X-Id"], p.method)Goal: Send headers.
Q6. Case insensitive headers
What does this print?
import requests
p = requests.Request("GET", "https://x.io", headers={"Accept": "text/html"}).prepare()
print(p.headers["accept"])Goal: Know header behaviour.
Q7. Build a Response by hand
Create requests.models.Response(), set status_code to 404, and print its ok attribute.
Goal: Understand Response.ok.
Q8. Raise on error
Create a Response with status_code 500 and call raise_for_status inside try. Print 'failed' when HTTPError is raised.
Goal: Handle errors.
Q9. ok for 301
What does this print?
import requests
r = requests.models.Response()
r.status_code = 301
print(r.ok)Goal: Understand Response.ok.
Q10. json is a method
This code does not give the data. Fix it.
import requests
r = requests.models.Response()
r._content = b'{"n": 5}'
print(r.json["n"])Goal: Call json().
Q11. Missing timeout
What is wrong with requests.get('https://api.example.com/data') in a script that must never hang?
Goal: Use timeouts.
Q12. Do not name it requests.py
Your file is named requests.py and import requests fails oddly. Why?
Goal: Avoid name clashes.
Q13. Fix the string join
Fix this code so params builds the URL.
import requests
url = "https://x.io/s?q=" + "a b"
print(url)Goal: Use params.
Q14. Count the pairs
What does this print?
import requests
p = requests.Request("GET", "https://x.io/s", params={"a": 1, "b": 2, "c": 3}).prepare()
print(p.url.count("&"))Goal: Read built URLs.
Q15. Choose text or content
Which attribute should you write to a file when you download a PNG image?
Goal: Choose the right attribute.
Q16. Why Session
Give one reason to use requests.Session.
Goal: Know Session.
Q17. Catch everything
Which exception class catches all errors raised by requests?
Goal: Handle exceptions.
Q18. Weather call plan
You call a weather API for city 'Pune' with key stored in a variable. Describe the requests call you would write.
Goal: Plan an API call.
Q19. Round trip a Response
Build a Response whose body is b'{"a": [1, 2]}' and print the second item of a.
Goal: Read JSON bodies.