<jupyter_start><jupyter_text>_El maravilloso mundo de las_ **APIs** o EL RETORNO DE JSON API: Interfaz de Programación de AplicacionesConjunto de definiciones y protocolos que se utiliza para desarrollar e integrar el software de las aplicaciones, permitiendo la comunicación entre dos aplicaciones de software a través de un conjunto de reglas. Listado de **APIs** for free: https://github.com/public-apis/public-apis<jupyter_code>import json
import requests

import pandas as pd
from pandas.io.json import json_normalize
import requests
import json

file_endpt = 'https://api.gdc.cancer.gov/data/'
file_uuid = 'd853e541-f16a-4345-9f00-88e03c2dc0bc'
response = requests.get(file_endpt + file_uuid)

# OUTPUT METHOD 1: Write to a file.
file = open("sample_request.json", "w")
file.write(response.text)
file.close()
https://api.gdc.cancer.gov/data
url_s = "https://api.gdc.cancer.gov/data"
endpoint = "api/qotd"
url_w = url_s + endpoint
requests.get(url_w)
qotd = requests.get(url_w).json()
qotd
qotd["quote"]
cita = qotd["quote"]
fecha = qotd["qotd_date"][:10]
autor = cita["author"]
cita_texto = cita["body"]

print("La frase del día", fecha, "es de", autor, "y es la siguiente:\n\n" + cita_texto)
json_normalize(qotd)<jupyter_output><empty_output><jupyter_text>API sin token **¿Qué es importante cuando tratamos con APIs?**Leer la documentación porque, si no lo hacemos, no sabemos cómo usarla. https://pokeapi.cohttps://pokeapi.co/docs/v2pokemon ------------------ Objetivo: Tener todos los nombres de pokemons junto con su url-----------------<jupyter_code># No todas las APIs devuelven todos los posibles valores debido a limitación de recursos

url = "https://pokeapi.co/api/v2/pokemon"
poke_json = requests.get(url).json()
poke_json                 
json_normalize(poke_json)
poke_json["next"]
url_new = 'https://pokeapi.co/api/v2/pokemon?offset=0&limit=65'

answer = requests.get(url_new).json()
answer
answer = requests.get(poke_json["next"]).json()
answer
# Cogemos todos los pokemons

answer = requests.get("https://pokeapi.co/api/v2/pokemon?offset=0&limit=999999").json()
answer
df_pokemons = pd.DataFrame(answer)
df_pokemons
df2 = pd.DataFrame(answer["results"])
df2
l1 = [2, 4]
l2 = ["a", "b"]
l1.extend(l2)
l1
poke_json
pokemon = [] # para contener todos los resultados de la api
poke_dict = {"name":"url"}

pokemon.extend(poke_json["results"])
pokemon
%%time
pokemon_api_url = "https://pokeapi.co/api/v2/pokemon"
poke_json = requests.get(pokemon_api_url).json()
pokemon = []

# Almacenamos 40 pokemons realizando peticiones hasta que la lista de pokemons tenga 40 o más pokemons
while len(pokemon) < 40:
    pokemon.extend(poke_json["results"])
    next_url = poke_json["next"]
    poke_json = requests.get(next_url).json()
print(len(pokemon))
pokemon
poke_json

%%time 
pokemon_api_url = "https://pokeapi.co/api/v2/pokemon"
poke_json = requests.get(pokemon_api_url).json()
pokemon = []

print(poke_json["next"])

import time
while poke_json["next"] != None:
    pokemon.extend(poke_json["results"])
    next_url = poke_json["next"]
    poke_json = requests.get(next_url).json()
    print(poke_json["next"])
    #time.sleep(1)  # Se pare un segundo
pokemon.extend(poke_json["results"])

print(len(pokemon))
pokemon
diccionario_pokemons_url = {}
for i, e in enumerate(pokemon):
    nombre_pokemon = pokemon[i]["name"]
    url_pokemon = pokemon[i]["url"]
    diccionario_pokemons_url[nombre_pokemon] = url_pokemon
diccionario_pokemons_url
df = pd.DataFrame(diccionario_pokemons_url, index=["url"])
df = df.T
df
# Para acceder al índice de cualquier DataFrame
print(type(df.T.index.values))
df.index
diccionario_pokemons_url
for nombre_pokemon, url in diccionario_pokemons_url.items():
    peticion_api_url = requests.get(url).json()
    print(nombre_pokemon)
    print(url)
    break

peticion_api_url
pd.DataFrame(peticion_api_url["abilities"])
for nombre_pokemon, url in diccionario_pokemons_url.items():
    peticion_api_url = requests.get(url).json()
    print(nombre_pokemon)
    print(url)
    break
peticion_api_url["types"]
pd.DataFrame(peticion_api_url["types"])
pd.DataFrame(peticion_api_url["types"]).type.values[0]
type_poke = pd.DataFrame(peticion_api_url["types"]).type.values[0]["url"]
type_poke
peticion_api_url = requests.get(type_poke).json()
peticion_api_url<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1372367507521407, 'fraction_numerical': 0.013422818791946308, 'mean_word_length': 5.431547619047619, 'pattern_counts': {'":': 1, '<': 10, '<?xml version=': 0, '>': 9, 'https://': 11, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '250885', 'license': 'MIT', 'n_tokens_mistral': 1692, 'n_tokens_neox': 1673, 'n_words': 338, 'path': 'week4_EDA_np_pd_json_apis_regex/day5_matplotlib_I_api/theory/apis/api_no_token.ipynb', 'repo_name': 'paleomau/MGOL_BOOTCAMP', 'size': '4321'}