The advantages of APIs
How to create and process API requests
The JSON data format
# Make a get request to get the latest position of the ISS from the OpenNotify API.
response = requests.get("http://api.open-notify.org/iss-now.json")
status_code = response.status_code
print(status_code)
print(response.json()['iss_position'])
Here are some codes that are relevant to GET requests:
200 - Everything went okay, and the server returned a result (if any).
301 - The server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint's name has changed.
401 - The server thinks you're not authenticated. This happens when you don't send the right credentials to access an API (we'll talk about this in a later mission).
400 - The server thinks you made a bad request. This can happen when you don't send the information the API requires to process your request, among other things.
403 - The resource you're trying to access is forbidden; you don't have the right permissions to see it.
404 - The server didn't find the resource you tried to access.
# Enter your answer below.
response = requests.get("http://api.open-notify.org/iss-pass")
status_code = response.status_code
# Enter your answer below.
response = requests.get("http://api.open-notify.org/iss-pass.json")
status_code = response.status_code
# Set up the parameters we want to pass to the API.
# This is the latitude and longitude of New York City.
parameters = {"lat": 40.71, "lon": -74}
# Make a get request with the parameters.
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
# Print the content of the response (the data the server returned)
print(response.content)
# This gets the same data as the command above
response = requests.get("http://api.open-notify.org/iss-pass.json?lat=40.71&lon=-74")
print(response.content)
there's a format we call JSON ,This format encodes data structures like lists and dictionaries
as strings to ensure that machines can read them easily.
JSON is the primary format for sending and receiving data through APIs.
Python offers great support for JSON through its json library. We can convert lists and dictionaries to JSON.
The JSON library has two main methods:
dumps -- Takes in a Python object, and converts it to a string
loads -- Takes a JSON string, and converts it to a Python object
# Make a list of fast food chains.
best_food_chains = ["Taco Bell", "Shake Shack", "Chipotle"]
print(type(best_food_chains))
# Import the JSON library.
import json
# Use json.dumps to convert best_food_chains to a string.
best_food_chains_string = json.dumps(best_food_chains)
print(type(best_food_chains_string))
# Convert best_food_chains_string back to a list.
print(type(json.loads(best_food_chains_string)))
# Make a dictionary
fast_food_franchise = {
"Subway": 24722,
"McDonalds": 14098,
"Starbucks": 10821,
"Pizza Hut": 7600
}
# We can also dump a dictionary to a string and load it.
fast_food_franchise_string = json.dumps(fast_food_franchise)
print(type(fast_food_franchise_string))
fast_food_franchise_2 = json.loads(fast_food_franchise_string)
# Make the same request we did two screens ago.
parameters = {"lat": 37.78, "lon": -122.41}
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
# Get the response data as a Python object. Verify that it's a dictionary.
json_data = response.json()
print(type(json_data))
print(json_data)
# Make the same request we did two screens ago.
parameters = {"lat": 37.78, "lon": -122.41}
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
# Get the response data as a Python object. Verify that it's a dictionary.
json_data = response.json()
print(type(json_data))
print(json_data)
first_pass_duration = json_data["response"][0]["duration"]
# Headers is a dictionary
print(response.headers)
content_type = response.headers["content-type"]
print(content_type)
# Call the API here.
response = requests.get("http://api.open-notify.org/astros.json")
json_data = response.json()
print(json_data)
in_space_count = json_data["number"]
print(in_space_count)
How to authenticate with APIs
The different types of API requests
1. Introduction
2. API Authentication
3. Endpoints and Objects
4. Other Objects
5. Pagination
6. User-Level Endpoints
7. POST Requests
8. PUT/PATCH Requests
9. DELETE Requests
10. Further Exploration
11. Takeaways
Authenticating with an API
The different types of API requests
https://cheatography.com/ecdk1234/cheat-sheets/timescale/
import requests
words = 30
paragraphs = 1
formats = 'text'
response = requests.get(f"https://alexnormand-dino-ipsum.p.rapidapi.com/?format={formats}&words={words}¶graphs={paragraphs}",
headers={
"X-RapidAPI-Host": "alexnormand-dino-ipsum.p.rapidapi.com",
"X-RapidAPI-Key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
)
print(response.text)
import requests
params = {"words": 10, "paragraphs": 1, "format": "json"}
response = requests.get(f"https://alexnormand-dino-ipsum.p.rapidapi.com/", params=params,
headers={
"X-RapidAPI-Host": "alexnormand-dino-ipsum.p.rapidapi.com",
"X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
)
print (type(response.json()))
print(response.json())
In simple terms, an API endpoint is the point of entry in a communication channel when two systems are interacting.
It refers to touchpoints of the communication between an API and a server.
The endpoint can be viewed as the means from which the API can access the resources they need from a server to perform
their task. An API endpoint is basically a fancy word for a URL of a server or service.
We all know that APIs operate through ‘requests’ and ‘responses.’ And when an API requests to access data from a web application
or server, a response is always sent back. The location where the API sends a request and where the response emanates is what
is known as an endpoint. Reputedly, the endpoint is the most crucial part of the API documentation since it’s what
the developer will implement to make their requests.
An API refers to a set of protocols and tools that allow interaction between two different applications.
In simple terms, it is a technique that enables third-party vendors to write programs that can easily interface with each other.
On the other hand, an endpoint is the place of interaction between applications.
API refers to the whole set of protocols that allows communication between two systems
while an endpoint is a URL that enables the API to gain access to resources on a server.
# importing the requests library
import requests
# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"
# location given here
location = "delhi technological university"
# defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}
# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
# extracting data in json format
data = r.json()
# extracting latitude, longitude and formatted address
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']
# printing the output
print("Latitude:%s
Longitude:%s
Formatted Address:%s"
%(latitude, longitude,formatted_address))
Making a POST request
# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"
# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"
# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''
# data to be sent to api
data = {'api_dev_key':API_KEY,
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
pastebin_url = r.text
print("The pastebin URL is:%s"%pastebin_url)
POST method – Python requests
requests.post(url, params={key: value}, args)
import requests
# Making a POST request
r = requests.post('https://httpbin.org/post', data ={'key':'value'})
# check status code for response recieved
# success code - 200
print(r)
# print content of request
print(r.json())
GET method – Python requests
requests.get(url, params={key: value}, args)
import requests
# Making a GET request
r = requests.get('https://api.github.com/users/naveenkrnl')
# check status code for response received
# success code - 200
print(r)
# print content of request
print(r.content)
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print request object
print(response.url)
# print status code
print(response.status_code)
Authentication using Python Requests
# import requests module
import requests
from requests.auth import HTTPBasicAuth
# Making a get request
response = requests.get('https://api.github.com/user,',
auth = HTTPBasicAuth('user', 'pass'))
# print request object
print(response)
SSL Certificate Verification
# import requests module
import requests
# Making a get request
response = requests.get('https://expired.badssl.com/')
# print request object
print(response)
# import requests module
import requests
# Making a get request
response = requests.get('https://github.com', verify ='/path/to/certfile')
# print request object
print(response)
response.ok – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print response
print(response)
# print if status code is less than 400
print(response.ok)
response.url – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('http://api.github.com')
# print response
print(response)
# print url
print(response.url)
response.headers – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com')
# print response
print(response)
# print headers of response
print(response.headers)
response.json() – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com')
# print response
print(response)
# print json content
print(response.json())
>>> from requests.auth import HTTPDigestAuth
>>> url = 'https://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
>>> import requests
>>> from requests_oauthlib import OAuth1
>>> url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
>>> auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
... 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
>>> requests.get(url, auth=auth)
HEAD method – Python requests
requests.head(url, params={key: value}, args)
import requests
# Making a HEAD request
r = requests.head('https://httpbin.org/', data ={'key':'value'})
# check status code for response recieved
# success code - 200
print(r)
# print headers of request
print(r.headers)
# checking if request contains any content
print(r.content)
import requests
# Making a get request
response = requests.get('https://api.github.com')
# prinitng request text
print(response.text)
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print response
print(response)
# print the reason
print(response.reason)
# ping an incorrect url
response = requests.get('https://geeksforgeeks.org / naveen/')
# print response
print(response)
# print the reason now
print(response.reason)
response.status_code – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('https://api.github.com/')
# print response
print(response)
# print request status_code
print(response.status_code)
response.is_redirect – Python requests
# import requests module
import requests
# Making a get request
response = requests.get('https://geeksforgeeks.org')
# print response
print(response)
# print is_redirect Flag
print(response.is_redirect)
https://www.geeksforgeeks.org/post-method-python-requests/?ref=rp