Calling a REST API from django view - python

Is there any way to make a RESTful api call from django view?
I am trying to pass header and parameters along a url from the django views. I am googling from half an hour but could not find anything interesting.
Any help would be appreciated

Yes of course there is. You could use urllib2.urlopen but I prefer requests.
import requests
def my_django_view(request):
if request.method == 'POST':
r = requests.post('https://www.somedomain.com/some/url/save', params=request.POST)
else:
r = requests.get('https://www.somedomain.com/some/url/save', params=request.GET)
if r.status_code == 200:
return HttpResponse('Yay, it worked')
return HttpResponse('Could not save data')
The requests library is a very simple API over the top of urllib3, everything you need to know about making a request using it can be found here.

Yes i am posting my source code it may help you
import requests
def my_django_view(request):
url = "https://test"
header = {
"Content-Type":"application/json",
"X-Client-Id":"6786787678f7dd8we77e787",
"X-Client-Secret":"96777676767585",
}
payload = {
"subscriptionId" :"3456745",
"planId" : "check",
"returnUrl": "https://www.linkedin.com/in/itsharshyadav/"
}
result = requests.post(url, data=json.dumps(payload), headers=header)
if result.status_code == 200:
return HttpResponse('Successful')
return HttpResponse('Something went wrong')
In case of Get API
import requests
def my_django_view(request):
url = "https://test"
header = {
"Content-Type":"application/json",
"X-Client-Id":"6786787678f7dd8we77e787",
"X-Client-Secret":"96777676767585",
}
result = requests.get(url,headers=header)
if result.status_code == 200:
return HttpResponse('Successful')
return HttpResponse('Something went wrong')

## POST Data To Django Server using python script ##
def sendDataToServer(server_url, people_count,store_id, brand_id, time_slot, footfall_time):
try:
result = requests.post(url="url", data={"people_count": people_count, "store_id": store_id, "brand_id": brand_id,"time_slot": time_slot, "footfall_time": footfall_time})
print(result)
lJsonResult = result.json()
if lJsonResult['ResponseCode'] == 200:
print("Data Send")
info("Data Sent to the server successfully: ")
except Exception as e:
print("Failed to send json to server....", e)

Related

How do I use Riot Games API with an API key?

I was trying to connect to the Riot Games API with the Python requests module, and it keeps giving me a 401 error. I added an API key, but it still says unauthorized. If anyone knows what is wrong with the code it would be appreciated.
I have tried tinkering and all I have this code:
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"Authorization": "Bearer " + API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
All I really have concluded is that the API key itself is not the issue, it is the request call.
It looks like Riot Games API uses the header X-Riot-Token to pass the authentication token, not Authorization, for some reason.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"X-Riot-Token": API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
You can also pass the API key as a query string parameter, however this can be slightly less secure in some scenarios.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot?api_key=" + API_KEY
response = requests.get(URL)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
Use your api key as a parameter rather than a header.
https://americas.api.riotgames.com/riot/?api_key=YOUR-API-KEY
Here is some help I found: https://apipheny.io/riot-games-api/#:~:text=All%20API%20calls%20to%20Riot,re%20making%20the%20request%20on.

How to pass a file from a URL via Python to an API?

I'm trying to use an API where you give it a CSV file and it validates it. For this API you pass it a file.
What I'm trying to do is this:
import requests
import urllib3
api_url="https://validation.openbridge.io/dryrun"
file_url = 'http://winterolympicsmedals.com/medals.csv'
http = urllib3.PoolManager()
response = http.request('GET', file_url)
data = response.data.decode('utf-8')
headers = {
# requests won't add a boundary if this header is set when you pass files=
'Content-Type': 'multipart/form-data',
}
response = requests.post(api_url, headers=headers, files=data)
I'm getting an error I don't quite understand:
'cannot encode objects that are not 2-tuples'
I'm fairly new to python, I'm mostly experienced in other languages but what I think the issue is that I'm probably passing the API the data in the file instead of giving it the file.
Any suggestions on what I"m doing wrong and how I can pass that file to the API?
For anyone who stumbles across this off google in the future. I figured out how to do it.
import requests
import urllib3
api_url="https://validation.openbridge.io/dryrun"
file_url="http://winterolympicsmedals.com/medals.csv"
remote_file = urllib3.PoolManager().request('GET', file_url)
response = requests.post(url=api_url,
json={'data': {'attributes': {'is_async': True }}},
files={ "file": remote_file},
allow_redirects=False)
if response.ok:
print("Upload completed successfully!")
print()
print("Status Code: ")
print(response.status_code)
print()
print(response.headers['Location'])
print()
else:
print("Something went wrong!")
print()
print("Status Code: ")
print(response.status_code)
print()
print(response.text)
print()

Schiphol flight api, get flight information with python gets error

I'm trying to get data from a public api from schiphol (airport in Amsterdam).
Im getting this api from https://api.schiphol.nl/public-flights/flights.
I'm using python to get the flight data. In my code I get the error that the "app_id" is none while this is filled in....
the full error from the console:
Usage: flight_info_api.py [options]
flight_info_api.py: error: Please provide an app id (-i, --app_id)
Can anybody see what is going wrong?
My code:
import requests
import sys
import optparse
def callPublicFlightAPI(options):
url = 'https://api.schiphol.nl/public-flights/flights'
headers = {
'resourceversion': 'v4',
'app_id': 'b209eb7f',
'app_key': '0b6c58b5ae4595dd39785b55f438fc70'
}
try:
response = requests.request('GET', url, headers=headers)
except requests.exceptions.ConnectionError as error:
print(error)
sys.exit()
if response.status_code == 200:
flightList = response.json()
print('found {} flights.'.format(len(flightList['flights'])))
for flight in flightList['flights']:
print('Found flight with name: {} scheduled on: {} at {}'.format(flight['flightName'],
flight['scheduleDate'],
flight['scheduleTime']))
else:
print('''Oops something went wrong Http response code: {}{}'''.format(response.status_code, response.text))
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-i', '--app_id', dest='app_id',
help='App id used to call the API')
parser.add_option('-k', '--app_key', dest='app_key',
help='App key used to call the API')
(options, args) = parser.parse_args()
if options.app_id is None:
parser.error('Please provide an app id (-i, --app_id)')
if options.app_key is None:
parser.error('Please provide an app key (-key, --app_key)')
callPublicFlightAPI(options)
You need to add this to your headers:
'Accept': 'application/json'
Good luck.
EDIT:
Basically, Since you would like to receive your data as json, You will have to add 'Accept': 'application/json' to your headers. In this case, your headers will look like this:
headers = {
'Accept': 'application/json',
'resourceversion': 'v4',
'app_id': YOUR_APP_ID,
'app_key': YOUR_APP_KEY
}
And when you are going to make a request, you have to add the headers in the parameter. Your request is going to look like this:
response = requests.get(URL, headers=headers)
I hope this helps!

(Python) How to check http response on status

can someone tell me how to check the statuscode of a HTTP response with http.client? I didn't find anything specifically to that in the documentary of http.client.
Code would look like this:
if conn.getresponse():
return True #Statuscode = 200
else:
return False #Statuscode != 200
My code looks like that:
from urllib.parse import urlparse
import http.client, sys
def check_url(url):
url = urlparse(url)
conn = http.client.HTTPConnection(url.netloc)
conn.request("HEAD", url.path)
r = conn.getresponse()
if r.status == 200:
return True
else:
return False
if __name__ == "__main__":
input_url=input("Enter the website to be checked (beginning with www):")
url = "http://"+input_url
url_https = "https://"+input_url
if check_url(url_https):
print("The entered Website supports HTTPS.")
else:
if check_url(url):
print("The entered Website doesn't support HTTPS, but supports HTTP.")
if check_url(url):
print("The entered Website supports HTTP too.")
Take a look at the documentation here, you simply needs to do:
r = conn.getresponse()
print(r.status, r.reason)
Update: If you want (as said in the comments) to check an http connection, you could eventually use an HTTPConnection and read the status:
import http.client
conn = http.client.HTTPConnection("docs.python.org")
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
If the website is correctly configured to implement HTTPS, you should not have a status code 200; In this example, you'll get a 301 Moved Permanently response, which means the request was redirected, in this case rewritten to HTTPS .

Handle google recaptcha with python / requests form

I was trying to find a way to fill a form then get the captcha response and found this code on stackoverflaw:
import urllib
import json
URIReCaptcha = 'https://www.google.com/recaptcha/api/siteverify'
recaptchaResponse = body.get('recaptchaResponse', None)
private_recaptcha = '6LdXXXXXXXXXXXXXXXXXXXXXXXX'
remote_ip = request.remote_addr
params = urllib.urlencode({
'secret': private_recaptcha,
'response': recaptchaResponse,
'remote_ip': remote_ip,
})
# print params
data = urllib.urlopen(URIReCaptcha, params).read()
result = json.loads(data)
success = result.get('success', None)
if success == True:
print 'reCaptcha passed'
else:
print 'recaptcha failed'
I tried it, but it says 'body' is not defined.
So instead I tried 'requests.get' but I get tons of mistakes.
Any clue on how i could make this work??
moreover, to validate my form I only need to pass the captcha-response to the form to make it work??
Thank you all for your answers
EDIT:
here is the link of the Post where i got it form:
How to validate a ReCaptcha response server side with Python?

Categories

Resources