Python APIs
GET Requests
import requests
resp = requests.get('https://www.___.com/___', params={"id":142256})
- This gets the content available from a server at the specified url.
- The content is in the form of a response object (see below).
- If the API doesn't require parameters, you can leave out the 'params' parameter.
- Pass the parameters as a dictionary.
- In addition to params, you can pass various other arguments such as timeout=__, cookies=__, ...
Alternative parameter passing
resp = requests.get('https://www.___.com/___?id=142256&name=bob')
- Add a '?' after the URL, and separate parameter name-value pairs with '&'.
Response object information
resp.text # For text content (e.g. HTML, JSON, text)
resp.content # For binary data (e.g. files, images)
resp.status_code # Status of request success (e.g. 200 or 404)
resp.headers['date'] # Date of server response
resp.headers['Content-Type'] # What kind of information is there (e.g. text/html)
resp.request.header # Metadata
resp.request.body # The information requested
resp.encoding # Character encoding (e.g. UTF-8)
resp.url # The URL used in the request
resp.json() # Response JSON parsed as a dictionary or list
...
- This gets the content available from a server at the specified url.
POST Requests
resp = requests.post('https://www.___.com/___', data={"name":"Bob","age":25})
- A POST request is for sending data to a server.
- You don't need to assign it to a variable, but doing so allows you to verify its success.
- Alternatively to "data", you can use "json" and pass parameters in json format.
PUT Requests
resp = requests.put('https://www.___.com/___', data={"name":"Bob","age":26})
- A PUT request is for updating data on a server, without creating a duplicate for existing entries.
DELETE Requests
resp = requests.delete('https://www.___.com/___')
- Used for removing resources (such as data or a file) from a server.
Challenge
Look up a free public API that sends a JSON response containing a list. Send a GET request, parse the data, and display each value in the list.
Completed