how to fetch data from API using python

Viewed 19169

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.

3 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)

Try requests it has two method get() and post()

Please try:

import requests
import json 
res = requests.get('paste your link here')
response = json.loads(res.text)

Yes python has requests lib to make a call to POST and GET methods

e.g.

import requests

url = 'web address'
params = {'key':'value'}
r = requests.get(url = URL, params = PARAMS) 
response = r.json() 
Related