Python Requests — get(), json()

Python requests are used to fetch content from web pages, which are identified by URLs (Uniform Resource Locators). When you make a get() request to a specific URL, it returns a response object containing the data from the webpage. The json() method converts this response data from JSON format into a Python data structure, typically a dictionary.

Exhibit 25.52 provides an example of the use of a Python request to retrieve data. The code uses the get() function to pull JSON data on the charmeleon pokemon from the pokemon api.

Pokemon: Extracting for Pokemon data with Pokemon API
# import requests module
import requests

# Making a get request for data on the charmeleon pokemon
response = requests.get('https://pokeapi.co/api/v2/pokemon/charmeleon')

# Convert pokemon.co JSON data to dictionary type and store in pk_charmeleon_data
pk_charmeleon_data = response.json()

# Print keys to reveal what information is contained in the data
print(pk_charmeleon_data.keys())  

# Print json data using loop
k = 1
for key in pk_charmeleon_data:
    print('\n' + key, ":", pk_charmeleon_data[key])
    if k == 3:  # limit to the first 3 keys
        break
    k += 1  # Increment k by 1        
dict_keys(['abilities', 'base_experience', 'cries', 'forms', 'game_indices', 'height', 'held_items', 'id', 'is_default', 'location_area_encounters', 'moves', 'name', 'order', 'past_abilities', 'past_types', 'species', 'sprites', 'stats', 'types', 'weight'])

abilities : [{'ability': {'name': 'blaze', 'url': 'https://pokeapi.co/api/v2/ability/66/'}, 'is_hidden': False, 'slot': 1}, {'ability': {'name': 'solar-power', 'url': 'https://pokeapi.co/api/v2/ability/94/'}, 'is_hidden': True, 'slot': 3}]

base_experience : 142

cries : {'latest': 'https://raw.githubusercontent.com/PokeAPI/cries/main/cries/pokemon/latest/5.ogg', 'legacy': 'https://raw.githubusercontent.com/PokeAPI/cries/main/cries/pokemon/legacy/5.ogg'} 

Exhibit 25.52 Code using function get() to extract for Pokemon data using the Pokemon API. Jupyter notebook.


Previous     Next

Use the Search Bar to find content on MarketingMind.