I have to get data from rest API using Python. How to send headers to retrieve data from API. Is there any module for requesting data from API.
5 Answers
Previous answers have covered the idea behind how to fetch data from an API using python. Requests library is a natural selection if you want to achieve this.
Documentation and ref: https://requests.readthedocs.io/en/master/
Installation: pip install requests or https://requests.readthedocs.io/en/master/user/install/#install
Coming to the last part - how to send headers to retrieve data from API?
You can pass headers as dictionary to the request.
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
response = requests.get(url, headers=headers)
Now you have the response object in response variable; now it's up to you what you want to achieve. e.g. If you want to see what is the response body as String;
print(response.text)
Comments
At first install 'request' library for making HTTP requests. pip install requests
import requests
userInput = str(input("Enter Poke Character: ")) #take user input
userInput = userInput.lower() #covert user input in lower case
def pokeGenerator():
if userInput: # if userInput is true
pokeApiUrl = requests.get(f'https://pokeapi.co/api/v2/pokemon/{userInput}')
#store api url in a variable
if pokeApiUrl.status_code == 200: #check api status
data = pokeApiUrl.json() #convert into python dict
print(f"Name: {data['name']}") #print name
print("Abilities")
for ability in data['abilities']: #loop through ability. Because it is a nested dictionary
print(ability['ability']['name'])
else: # if status code is not 200
return print("Character not found")
print(pokeGenerator())
if the status is 200 then the result will be:
Enter Poke Character: ditto
Name: ditto
Abilities:
limber
imposter
None
Process finished with exit code 0
if the status is not ok then:
Enter Poke Character: dobubjwdbuwdb
Character not found
None
Process finished with exit code 0
Comments
The easiest way to do this is to use the requests module
# pip install requests
import requests
# Send a GET request to a website
res = requests.get(
"https://www.example.com/", # The URL of the API you want to access
params={"key1": "value1", "key2": "value2"}, # The parameters you want to pass to the API (like "?key=value" at the end of the URL)
data={"key1": "value1", "key2": "value2"}, # The data you want to send to the API
headers={"header1": "value1", "header2": "value2"}, # The headers you want to send to the API
cookies={"cookie1": "value1", "cookie2": "value2"}, # The cookies you want to send to the API
auth=("username", "password"), # The authentication credentials you want to send to the API (some websites require this)
timeout=5, # The maximum site response time (in seconds)
allow_redirects=True, # Whether or not to follow redirects
)
# Send a POST request to a website
res = requests.post(...)
# Send a PUT request to a website
res = requests.put(...)
# Send a DELETE request to a website
res = requests.delete(...)
if res.status_code == 200:
output = res.json()
print(output)
If for some reason you want to use a standard module, you can do this with urllib
import urllib.request
import json
response = urllib.request.urlopen("https://www.example.com")
if response.getcode() == 200:
output = json.loads(response.read())
print(output)
If you need to perform this action in an asychronous function, you can use aiohttp
# pip install aiohttp
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://www.example.com") as response:
if response.status == 200:
output = await response.json()
print(output)
asyncio.run(main())
requestsmodule is useful for taking to the web. What have you tried so far?