httpx.RemoteProtocolError: peer closed connection without sending complete message body - python

I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong.
from httpx import stream
with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response:

I've got the same error when using httpx via openapi-client autogenerated client
response = httpx.request(verify=client.verify_ssl,**kwargs,)
It turned out in kwargs parameter headers contained wrong authorization token.
So basically in my case that error meant "authorization error".
You might want to check if what you sending in your parameters is correct too.

Related

Why do I get a 401 status code from the discord api?

I'm trying to validate discord token, sending requests to the discord api, this was working but for some reason it stopped, this is my code:
def validate():
headers = {'Content-Type': 'application/json', 'authorization': "my_token_here"}
request = requests.get("https://discordapp.com/api/v6/users/#me/library", headers=headers)
if(request.status_code == 200):
print("\033[32m[+] Valid Token.\033[m")
else:
print("\033[33m[-] Invalid Token.\033[m")
I put my bot token and still the status is 401, it was working before, can someone help me and explain what happened
Edit:
I noticed that I had placed a slash after library and then I started to receive the unauthorized code 401, even though the token is valid, why does this happen?
Try sending the call using HTTP and not HTTPS. I'm not sure this will solve the problem, but it might be worth a try.
Difference between HTTP and HTTPS:HTTPS is HTTP with encryption. The only difference between the two protocols is that HTTPS uses TLS (SSL) to encrypt normal HTTP requests and responses. As a result, HTTPS is far more secure than HTTP. A website that uses HTTP has http:// in its URL, while a website that uses HTTPS has https://.
Also, make sure that all parts of the address are spelled correctly. And if the API you are referring to belongs to you and make sure it is defined properly.

aiohttp, raising an error on GET, can't send GET request to https website

I have this code part that sends GET request:
proxy_auth = aiohttp.BasicAuth('proxy-username', 'proxy-password')
async with session.get('https://google.com', headers=headers, proxy='http://proxy_url.com', proxy_auth=proxy_auth) as response:
html = await response.text()
The problem is when I'm trying to GET https website it returns this exception:
ClientConnectorError: Cannot connect to host google.com:443 ssl:default [The parameter is incorrect]
This exception is thrown only when the website is provided by https, with http there's no exceptions.
The proxy is https but aiohttp only accepts http proxy, but I know there's some tricks to get it to work.
I found a solution for that problem. It happens because of the aiohttp library itself so we need to change the Event Policy Loop to asyncio.WindowsSelectorEventLoopPolicy()
Like that:
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

403 (Forbidden) error when using Fortnite Tracker api with urllib.request

I am attempting to get user statistics from the Fortnite tracker api.
I have an api key and am using the correct url as indicated in the documentation
Template url:
https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}
Desired url:
https://api.fortnitetracker.com/v1/profile/pc/xantium0
If I use this link in browser I get {"message":"No API key found in request"} (as I have not passed the API key) so the link should be correct. Also if I do not pass the api key with urllib then I still get a 403 error.
I have checked out how to pass a header in a request: How do I set headers using python's urllib?
and so far have this code:
import urllib.request as ur
request = ur.Request('https://api.fortnitetracker.com/v1/profile/pc/xantium0', headers={'TRN-Api-Key' : 'xxx'})
response = ur.urlopen(request)
print(response.read())
When run I get this error:
urllib.error.HTTPError: HTTP Error 403: Forbidden
403 checks out as:
HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that the server understood the request, but will not fulfill it. There are a number of sub-status error codes that provide a more specific reason for responding with the 403 status code.
https://en.wikipedia.org/wiki/HTTP_403
The response is the same if I don't pass the api key in the header.
I can only think of three reasons this code is not working:
I have passed the wrong header name (i.e. it's not TRN-Api-Key)
My code is incorrect and I am not actually passing a header to the server
I have been banned
My problem is that I think my code is correct:
From the documentation:
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
I have passed the url and I have passed the headers (wihout confusing with the data arguement). The api documentation also mentions it should be passed in the headers.
I am also quite sure I need to use the TRN-Api-Key as it is shown in the api documentation:
TRN-Api-Key: xxx
Also in this question (using Ruby):
header = {
key: "TRN-Api-Key: Somelong-api-key-here"
}
Or I have been banned (this is possible although I got the key 15 minutes ago) is there a way to check? Would this error be returned?
What is preventing me from getting the user statistics?
Try using requests, a pythonic, fast and widely used module.
import requests
url = 'https://api.fortnitetracker.com/v1/profile/pc/xantium0'
headers = {
'TRN-Api-Key' : 'xxx'
}
response = requests(url, headers=headers)
print('Requests was successful:', response.ok)
print(response.text)
If it doesn't work you can visit the url with your browser, then check the requests:
in Firefox press Cntrl+Shift+E, in Chrome Cntrl+E (or Inspect with Cntrl+Shift+I and then go to Network). Press on "https://api.fortnitetracker.com/v1/profile/pc/xantium0" and change the headers. On Firefox there's the button Modify and resend. Check the response and eventually, try to change the header api key name.
Hope this helps, let me know.

GET request via python script with access token

I'm facing some difficulties executing GET request with access token via python.
For some reason when I execute the request from POSTMAN I get the expected result, however, when using python I get connection error :
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I believe that my script is being blocked by the server to prevent scrapping attempts, but I'm not sure.
This is what I'm running via POSTMAN :
https://www.operation.io/web/alerts?access_token=6ef06fee265de1fa640b6a444ba47--z&envId=58739be2c25e76a202c9dd3e&folderId=active&sortBy=status
And this is what I'm running from inside the script :
response = requests.get('https://www.operation.io/web/alerts', headers={'Authorization': 'access_token 6ef06fee265de1fa640b6a444ba47--z'})
Please notice that the url and the access token are not real, so please don't try to use.
How can I make it work via the script and not only via postman?
Thank you for your help/
It's hard to tell without actually being able to test the solutions, but I would suggest 2 hacks that worked for me in the past:
Change "Authorization" to "authorization"
Change "6ef06fee265de1fa640b6a444ba47--z" to "Token 6ef06fee265de1fa640b6a444ba47--z" (add a space as well)
Put it all together:
response = requests.get('https://www.operation.io/web/alerts', headers={'authorization': 'Token 6ef06fee265de1fa640b6a444ba47--z'})
Since via postman you're sending the token as query param(as opposed to header), you can try this :
response = requests.get('https://www.operation.io/web/alerts', params={'access_token': '6ef06fee265de1fa640b6a444ba47--z'})
Assuming the API you're using accepts it as query param rather than as headers (which is my guess from the postman request)

failed API call - error 400

I've written a simple API call using requests and am getting an error 400 on executing the call. Can someone please tell me where I am going wrong? Thanks for the help. Here's the code i wrote -
import requests
params={
'api_key':'gozbsSP1fxqNSS5YjcFM7qcjjKch1tBB',
'api_secret':'HklHJCzfO87YyIC9DudGArVKJtioEhbO',
'image_url':'http://picz.in/data/media/7/study-in-canada-students.jpg'
}
r = requests.post(url='https://api-
us.faceplusplus.com/facepp/v3/detect',data=params)
print(r)
400 error code basically means it's a bad request. So it can be that you provided the wrong params for the api, or the api_key or api_secret is not correct.
Check the documentation of the API whether you are sending all the required params are there or not. If so check your secret keys and make sure it's the correct one.
Remeber to never post you API Keys on public forums like SO...
400 means its a bad request: the request you made is not what the server wanted.
(invalid arguments, wrong payload data, etc)
More info on 400 errors here:
https://airbrake.io/blog/http-errors/400-bad-request
The 400 Bad Request Error is an HTTP response status code that indicates that the server was unable to process the request sent by the client due to invalid syntax
Sometimes the response object will include information on why the request failed, but that's not always the case.

Categories

Resources