403 error on my Python REST API with Wordpress - python

I am following a simple example (or what I thought was simple) of creating a python script that used the REST api to connect to wordpress.
However, I am getting a 403 error. My credentials are correct because I can log in with them.
I have been working over this for awhile now. Can anyone see where my error might be? Thank you.
url = "https://prod-wp.xxxxxx.com/wp-json/wp/v2/posts"
user = "xxxxxx"
password = "xxxxxxxx"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)
<Response [403]>
EDIT
I have changed the code and this seems to work.
import requests
import os
from dotenv import load_dotenv
load_dotenv()
BASE_URL = 'https://website.com/wp-json'
WP_URL = os.getenv("WP_URL")
WP_USERNAME = os.getenv("WP_USERNAME")
WP_PASSWORD = os.getenv("WP_PASSWORD")
def get_headers():
wp_credentials = {'username': WP_USERNAME, 'password': WP_PASSWORD}
jwt_response = requests.post(f'{BASE_URL}/jwt-auth/v1/token', json=wp_credentials)
jwt_token = jwt_response.json()['token']
headers = {
"Authorization": "Bearer %s" % jwt_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
print(f'Headers are equal to: {headers}')
return headers
get_headers()

Related

Spotify Client Credentials Flow using Python

I'm trying to get a token using Spotify's Client Credentials Flow and Python, however I just get the following:
{"error":"invalid_client","error_description":"Invalid client"}
I'm following this guide - https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/
Using this example script as a starting point - https://www.w3schools.com/python/showpython.asp?filename=demo_requests_post_headers
Here's my code (I've changed the Base 64 encoded string that contains the client ID and client secret key):
import requests
url = 'https://accounts.spotify.com/api/token'
myobj = {'grant_type': 'client_credentials'}
#use the 'headers' parameter to set the HTTP headers:
x = requests.post(url, data = myobj, headers = {"Authorization": "Basic Base64EncodedStringHere==","Content-Type": "application/x-www-form-urlencoded"})
print(x.text)
If I change the last line to print(x), I just get: <Response [400]>
Clearly I'm doing something wrong, but I can't figure out what?
I had the same problem while following a tutorial but I manage to find a solution on the Spotify community.
import requests
import base64
client_id = "your client id here"
client_secret = "your client secret here"
encoded = base64.b64encode((client_id + ":" + client_secret).encode("ascii")).decode("ascii")
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + encoded
}
payload = {
"grant_type": "client_credentials"
}
response = requests.post("https://accounts.spotify.com/api/token", data=payload, headers=headers)
print(response.text)

How to upload an image with the wordpress api in Python?

I hope your are fine.
I would like to upload an image in my wordpress library from my computer.
I wrote few lines in Python that use Wordpress API.
It is working when I use 'Content-Type': 'application/x-www-form-urlencoded'
However, the content added is not an image.
When I change it with 'Content-Type': 'image/jpg' I get an error message which says:
Error 403 please forward this error screen to the site owner
What should I do, contact my web hosting company ?
Thank you all for you help
Here is my code:
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os
user = "user"
password = "pass"
url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
# headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'application/x-www-form-urlencoded','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
video = {
"title": "test",
"description": "description",
"media-type": "image",
}
r = requests.post(url + "/media", headers=headers, json=video)
print(r.text)
I solved the problem with this code
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os
user = "user"
password = "pass"
url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
image = {
"file": open("toto.png", "rb"),
"caption": "caption",
"description": "description",
}
r = requests.post(url + "/media", headers=headers, files=image)
print(r.text)
print(r)

Connecting to a rest API with python. How to setup headers & parameters?

i'm working on settin up a rest api with python, however i'm having some problem getting it to work.
I'm working with the TV DB rest api: https://api.thetvdb.com/swagger
and using python with Requests library to pull out the information.
My code is currently:
import json
import requests
URL = "https://api.thetvdb.com/"
API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"
headers = {"Accept": "application/json"}
params = {
"apikey": API_KEY,
"userkey": USER_KEY,
"username": USERNAME
}
resp = requests.post(URL + "login/", headers = headers ,params=params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
So far i'm only getting error code 401, not sure why.
Solved:
2 Things needed to be changed
1. The resp was changed into:
resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
The header had to have
"Content-Type": "application/json"
added to it :) It's now working, thanks everyone
The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.
Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))

Python JWT auth token does not authorize with django jwt api

i am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work.
is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend?
import requests
from urllib2 import Request, urlopen
import jwt
from requests_jwt import JWTAuth, payload_method
import json
def tryme(chats, payload, jwt):
#method1
res = requests.post(chats, json=payload)
print res.status_code
# error 401
# method2
req = requests.get(chats, params=payload)
print req.status_code
# error 401
# method3
req = Request(chats)
req.add_header('Authorization', 'Token token={}'.format(auth['token']))
req.add_header('content-type', 'application/json')
res = urlopen(req)
print res.status_code
# error 401
#method4
token = JWTAuth(jwt['token'])
out = requests.get(chats, auth=token)
print out.status_code
# error 401
out = requests.post(chats, auth=token)
print out.status_code
# error 401
def main():
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
auth = json.loads(requests.post(api_auth, json=payload).content)
# returns auth token
payload = {'Authorization': 'Token {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'Bearer {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'JWT {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
if __name__ == '__main__':
main()
this was solved. however i upgraded to python3.
import requests
import urllib3
urllib3.disable_warnings()
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# in python3 use urllib3.
http = urllib3.PoolManager()
res = http.request('GET', chats, headers=payload)
print(res.data)
in python2:
import requests
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# make sure you are using the right request (GET vs POST)
out = requests.get(chats, headers=token)
print out.content

How to access curl data with oauth in web.py

I have this code, it sends a request to my server which is run by web.py:
url = "https://sample.com/api"
auth_string = 'Basic ' + base64.encodestring('%s:%s' % ("usernamexxxx", "codexxxx"))[:-1]
headers = {"Content-Type": "application/json", "authorization": auth_string}
data = {"message":"WELCOME!..."}
req = urlfetch.fetch(url, method=urlfetch.POST, payload= simplejson.dumps(data), headers= headers)
response = req.content
So when I receive this kind of request in my web server I want to check if the username and code input to the request is valid or not? And how can I access the given data of the code above?
Probably you can access those headers via the os.environ dictionary.

Categories