APIs [Application Programming Interface]
- to querying a data source
- to retrieve dynamically generated data
API Server Interaction
- Server/client interaction through HTTP or HTTPS
- API can be independent of the implementation
Requests Module and APIs
- Requests Module handles HTTP or HTTPS interactions
- Requests containing URL and parameters are automatically encoded
- responses are packaged in a response object
- Resposne content can be in any format
- JSON is the most commong and easily parsed
- Other formats include XML, CSV and HTML
API Example
image of screenshot
import request
import json
url = 'https://universities.hipolabs.com/search'
p = {'country': 'United states', 'name': 'berkeley'}
response = requests.get(url, p)
if response.ok:
contents = json.loads(response.text)
# json.loads converts a json string into a python object
for e in contents:
print(e['name'], e['web_pages'])
API Example - Formatted JSON
[
{
"domains": ["berkeley.edu"],
"web_pages": ["http://www.berkeley.edu/"],
"state-province": null,
"country": "United States",
"Alpha_two_code": "US"
},
{
"domains": ["berkeleycitycollege.edu"],
"web_pages": ["http://www.berkeleycitycollege.edu/wp/"],
"state-province": null,
"country": "United States",
"Alpha_two_code": "US"
}
]
API Limitations
- Not all servers have APIs
- may require authentication and authorization
- no standards for parameters
- documentaion may be limited or non existent.