I am unable to connect with the pwnedpasswords API when I define a function and I get error "400", which is a bad request. I am using the following code:
import requests
def request_api_data(char):
url = 'https://api.pwnedpasswords.com/range/' + char
res = requests.get(url)
print(res)
request_api_data('123')
However, when I use this code without function then I get a response of "200" which is a good response.
import requests
url = 'https://api.pwnedpasswords.com/range/' + 'CBFDA'
res = requests.get(url)
print(res)
I don't understand why it becomes a bad request when I try to make it a function.
The problem is with the 123, if you try CBFDA in the first code it will work, it gives this error with 123:
"The hash prefix was not in a valid format"
This happens because 123 is not a valid hash prefix
Related
Working on a API project, in which I'm trying to get all the redirect urls from an API output such as https://urlscan.io/api/v1/result/39a4fc22-39df-4fd5-ba13-21a91ca9a07d/
Example of where I'm trying to pull the urls from:
"redirectResponse": {
"url": "https://www.coke.com/"
I currently have the following code:
import requests
import json
import time
#URL to be scanned
url = 'https://www.coke.com'
#URL Scan Headers
headers = {'API-Key':apikey,'Content-Type':'application/json'}
data = {"url":url, "visibility": "public"}
response = requests.post('https://urlscan.io/api/v1/scan/',headers=headers, data=json.dumps(data))
uuid = response.json()['uuid']
responseUrl = response.json()['api']
time.sleep(10)
req = requests.Session()
r = req.get(responseUrl).json()
r.keys()
for value in r['data']['requests']['redirectResponse']['url']:
print(f"{value}")
I get the following error: TypeError: list indices must be integers or slices, not str. Not sure what the best way to parse the nested json in order to get all the redirect urls.
A redirectResponse isn't always present in the requests, so the code has to be written to handle that and keep going. In Python that's usually done with a try/except:
for obj in r['data']['requests']:
try:
redirectResponse = obj['request']['redirectResponse']
except KeyError:
continue # Ignore and skip to next one.
url = redirectResponse['url']
print(f'{url=!r}')
trying to make post requests in python, i'm getting this error
import requests
token='Bearer aslkdjndskgns'
endpoint = "https://aap.xyz"
phone_number='9177903753951'
data = {"number":phone_number}
datas = str(data)
headers={"authorization":token}
a=(requests.post(endpoint, data=datas, headers=headers).json())
i'm getting this error
invalid character 'p' looking for beginning of value "
Please try below code, see if it resolves your issue.
import requests
token='Bearer aslkdjndskgns'
endpoint = 'https://aap.xyz'
data = {'number':'9177903753951'}
headers={"authorization":token}
a=(requests.post(endpoint, data=data, headers=headers).json())
print(a)
As this is the first time I'm trying this out, I do not know what is wrong with the problem. So it would be great if someone can help me solve this problem
The code I'm using is at the bottom page of this website: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html
Where it give example on how you can make HTTP request function and retrieve database on your query.
The code on the website is this.
query.py
import requests
import json
BASE_URL = 'http://pokeapi.co'
def query_pokeapi(resource_url):
url = '{0}{1}'.format(BASE_URL, resource_url)
response = requests.get(url)
if response.status_code == 200:
return json.loads(response.text)
return None
charizard = query_pokeapi('/api/v1/pokemon/charizard/')
sprite_uri = charizard['sprites'][0]['resource_uri']
description_uri = charizard['descriptions'][0]['resource_uri']
sprite = query_pokeapi(sprite_uri)
description = query_pokeapi(description_uri)
print
charizard['name']
print
description['description']
print
BASE_URL + sprite['image']
In my edit, I only change these print line at the bottom of this
query.py
print(charizard['name'])
print(description['description'])
print(BASE_URL + sprite['image'])
But i got this error instead
Traceback (most recent call last): File "query2.py", line 46, in
sprite_uri = charizard['sprites'][0]['resource_uri'] TypeError: 'NoneType' object is not subscriptable
query_pokeapi must be returning None, which would mean that your API call is not receiving a 200 HTTP response. I'd check your URL, to make sure it's properly formed. Test it in your web browser.
best practice would be to try-except your API call with an error message letting you know that your API call failed and otherwise routing the thread.
Update: reread and the sub scripting issue could be in any layer of your nested object.
Evaluate charizard['sprites'][0]['resource_uri']
step by step in your debugger.
When you call api requests.get(url) then its response is
More than one resource is found at this URI
you are using charizard['sprites'][0]['resource_uri'] on result and it's raising exception.
When I tried to get response then status code is 300 so
def query_pokeapi(resource_url) returning None value.
'{0}{1}'.format(BASE_URL, resource_url)
Update
it means at {0} BASE_URL will be places and at {1} resource_url will be places.
Complete url will be
url = '{0}{1}'.format(BASE_URL, resource_url)
url = 'http://pokeapi.co/api/v1/pokemon/charizard/'.
update
you can try
import json
charizard = query_pokeapi('/api/v1/pokemon/')
data = json.loads(charizard.content)
print data['objects'][0]['descriptions'][0]
result will be
{u'name': u'ekans_gen_1', u'resource_uri': u'/api/v1/description/353/'}
Update with complete code
import requests
import json
BASE_URL = 'http://pokeapi.co'
def query_pokeapi(resource_url):
url = '{0}{1}'.format(BASE_URL, resource_url)
response = requests.get(url)
if response.status_code == 200:
return json.loads(response.text)
return None
charizard = query_pokeapi('/api/v1/pokemon/')
print charizard['objects'][0]['descriptions'][0]
result will be:
{u'name': u'ekans_gen_1', u'resource_uri': u'/api/v1/description/353/'}
I'm connecting to a login protected API with a Python script here below.
import requests
url = 'https://api.json'
header = {'Content-Type': 'application/x-www-form-urlencoded'}
login = ('kjji#snm.com', 'xxxxx')
mnem = 'inputRequests':'{'inputRequests':'[{'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}]}}
r = requests.post(url, auth=login, data=mnem, headers=header)
print(r.json())
The connection is established but I am getting an error from the API because of the format of the data request.The original format is here below. I cannot find a way to enter this in the mnem here above:
inputRequests={inputRequests:
[
{function:"xxx",identifier:"xxx",mnemonic:"xxx"},
]
}
The error given is
C:\Users\xxx\Desktop>pie.py
File "C:\Users\xxx\Desktop\pie.py", line 6
mnem={'inputRequests':'{'inputRequests':'[{'function':'xxx','identifier':'xx','mnemonic':'xxx'}]}}
^
SyntaxError: invalid syntax
I am unsure on how to proceed from here. I cannot find anything in the requests documentation that points to how to insert several variables in the data field.
The requests module in Python receive protogenic Python dict as the JSON data in post request but not a string. Therefore, you may try to define mnem like this:
mnem = {
'inputRequests':[
{'function':'GDSP',
'identifier':'ibm',
'mnemonic':'IQ_TOTAL_REV'
}
]}
the data parameter should be a dictionary.
therefore to pass the three parameters try using:
mnem = {'function':'GDSP','identifier':'ibm','mnemonic':'IQ_TOTAL_REV'}
i met a problem by using requests.get() on kubernetes api
url = 'http://10.69.117.136:8080/api/v1/namespaces/"default"/pods/tas-core/'
json = requests.get(url)
print json.content
error code 404 will be returned as:
{"kind": "Status","apiVersion": "v1","metadata": {},"status": "Failure","message": "pods \"tas-core\" not found","reason": "NotFound","details": {"name": "tas-core","kind": "pods"},"code": 404}
but if i use GET/curl, the response could be returned successfully:
curl http://10.69.117.136:8080/api/v1/namespaces/"default"/pods/tas-core/
{"kind": "Pod","apiVersion": "v1","metadata": {"name": "tas-core","namespace":"default","selfLink": "/api/v1/namespaces/default/pods/tas-core","uid": "a264ce8e-a956-11e5-8293-0050569761f2","resourceVersion": "158546","creationTimestamp": "2015-12-23T09:22:06Z","labels": {"app": "tas-core"},"annotations": {"ctrl": "dynamic","oam": "dynamic"}},"spec": {"volumes":[ ...
further more shorter url works fine
url = 'http://10.69.117.136:8080/api/v1/namespaces/'
json = requests.get(url)
print json.content
{"kind":"NamespaceList","apiVersion":"v1","metadata":{"selfLink":"/api/v1/namespaces/","resourceVersion":"220452"},"items":[{"metadata":{"name":"default","selfLink":"/api/v1/namespaces/default","uid":"74f89440-a94a-11e5-9afd-0050569761f2","resourceVersion":"6","creationTimestamp":"2015-12-23T07:54:55Z"},"spec":{"finalizers":["kubernetes"]},"status":{"phase":"Active"}}]}
where did i wrong?
Making the request from requests and from command line sends it to different urls.
The requests request from Python code really tries to use url including the quotes.
curl from command line does strip the quotes (in other cases it escapes the quotes).
I am unable to test your real url for real requests, but I guess, that following might work:
url = 'http://10.69.117.136:8080/api/v1/namespaces/default/pods/tas-core/'
json = requests.get(url)
print json.content