Getting 401 response while making get request with bearer token (Python) - python

Here is my code---
token = APIUtilities()
auth_token = token.get_token(end_point=App_Config.BASE_URL+"/connect/token",
username="username", password="Password#", client_id="test")
headers = CaseInsensitiveDict()
headers["Accept"] = "*/*"
headers["Authorization"] = "Bearer "+auth_token
headers["User-Agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
response = requests.get(App_Config.BASE_URL+"/api/customers", headers=headers)
assert_that(response.status_code).is_equal_to(requests.codes.ok)
I am getting the token but not sure why I am getting 401 error again and again. Please help me to resolve this.

You are not sending the auth_token in
requests.get(App_Config.BASE_URL+"/api/customers", headers=headers)
It should be something like :
requests.get(App_Config.BASE_URL+"/api/customers", headers={'Authorization': 'auth_token'})

Issue is resolved. Above code snippet is fine, problem was with token generation method. It was returning something wrong which I corrected and now code is fine.

Related

How to comment on clickup with python?

I want to comment on a specific task in clickup but it responses 401 error.
url = "https://api.clickup.com/api/v2/task/861m8wtw3/comment"
headers = {
"Authorization": "Bearer <my api key>",
"Content-Type": "application/json"
}
# comment = input('Type your comment text: \n')
comment = 'test comment'
data = {
"content": f"{comment}"
}
response = requests.post(url, headers=headers, json=data)
and the output is:
<Response [401]>
what is the problem?
i tried to add mozilla headers as the user agent key:
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
but still get the 401 error!
Seems to me like your getting detected.
Try using Selenium-Profiles
It looks like the issue is with the Authorization header. Make sue that the header only includes the API token string, without 'Bearer' in front of it. Like so:
headers = {
"Authorization": "<your api token>",
"Content-Type": "application/json"
}

How would I log into Instagram using BeautifulSoup4 and Requests, and how would I determine it on my own?

I've looked at these two posts on Stack Overflow so far:
I can't login to Instagram with Requests and Instagram python requests log in without API. Both of the solutions don't work for me.
How would I do this now, and how would someone go about finding what requests to make where? To make that clearer, if I were to send a post request to log in, how would I go about knowing what and where to send it?
I don't want to use Instagram's API or Selenium, as I want to try out Requests and (maybe) bs4.
In case you'd want some code:
import requests
main_url = 'https://www.instagram.com/'
login_url = main_url+'accounts/login/ajax'
user_agent = 'User-Agent: Mozilla/5.0 (iPad; CPU OS 6_0_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A523 Safari/8536.25'
session = requests.session()
session.headers = {"user-agent": user_agent}
session.headers.update({'Referer': main_url})
req = session.get(main_url)
session.headers.update({'set-cookie': req.cookies['csrftoken']})
print(req.status_code)
login_data = {"csrfmiddlewaretoken": req.cookies['csrftoken'], "username": "myusername", "password": "mypassword"}
login = session.post(login_url, data=login_data, allow_redirects=True)
print(login.status_code)
session.headers.update({'set-cookie': login.cookies['csrftoken']})
cookies = login.cookies
print(login.headers)
print(login.status_code)
This gives me a 405 error.
you can use this code to login to instagram
import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime
link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'
time = int(datetime.now().timestamp())
payload = {
'username': 'login',
'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:your_password',
'queryParams': {},
'optIntoOneTap': 'false'
}
with requests.Session() as s:
r = s.get(link)
csrf = re.findall(r"csrf_token\":\"(.*?)\"", r.text)[0]
r = s.post(login_url, data=payload, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"Referer": "https://www.instagram.com/accounts/login/",
"x-csrftoken": csrf
})
print(r.status_code)
Hint: I needed to modify the line
r = s.get(link)
into
r = s.get(link,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})
to get a proper reply. Without it, I got "page not found" using JupyterNotebook.

Status 500 using requests in Python

So I am working on sending images to an url. And I planned to use Python to make the POST requests.
My code looks like this:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}
response = requests.request('POST', url, headers=headers, files={'file':open('1-watermarked-page.PNG', 'rb')})
print (response.status_code)
When I run this, I am getting a status code of 500.
I tried to replace the "files" parameter by "data" and it gives me an error of 413:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'}
response = requests.request('POST', url, headers=headers, data={'file':open('1-watermarked-page.PNG', 'rb')})
print (response.status_code)
Can anyone please tell me where am I making a mistake?
Thanks!
The problem is that we have to send the data to a post request in the JSON format but we are sending it as a dictionary which makes the request a bad request. So the best approach known to me is to convert the data to JSON format (this might be because of the parsing that takes place at the server side)
import json
data = data={'file':open('1-watermarked-page.PNG', 'rb')}
response = request.post("url",json.dumps(data))
# json.dumps(data) converts data to json format
This worked for me, let me know if it worked for you

Not able to login to a website using requests python package

I am using the following script to login to https://www.mbaco.com/login. While I am not getting any error, I can't access the protected pages of the website. Plz help.
import requests
url = 'https://www.mbaco.com/login'
payload = {
'_username':"mysuername",
'_password':"password"
}
session = requests.session()
r = session.post(url, data=payload)
You have the wrong url, the post is to https://www.mbaco.com/login_check, it is also a good to add a user-agent:
import requests
headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"}
url = 'https://www.mbaco.com/login_check'
payload = {
'_username':"mysuername",
'_password':"password"
}
session = requests.session()
r = session.post(url, data=payload, headers=headers)
If you want to see what gets posted and to where, open developer tools or firebug and you can see exactly what is happening, in this case you can see under the other tab exactly what is posted and to where:

Python Requests Get XML

If I go to http://boxinsider.cratejoy.com/feed/ I can see the XML just fine. But when I try to access it using python requests, I get a 403 error.
blog_url = 'http://boxinsider.cratejoy.com/feed/'
headers = {'Accepts': 'text/html,application/xml'}
blog_request = requests.get(blog_url, timeout=10, headers=headers)
Any ideas on why?
Because it's hosted by WPEngine and they filter user agents.
Try this:
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36"
requests.get('http://boxinsider.cratejoy.com/feed/', headers={'User-agent': USER_AGENT})

Categories