Home > database >  Python - how to authenticate the server and the api?
Python - how to authenticate the server and the api?

Time:05-22

I am trying to send an API request to a server that needs http authentication.

The (Wordpress server) is set to authenticate the API using basic authentication.

First I am setting the session using the code

with requests.sessions.Session() as session:
    session.auth = ('my_user', 'my_password')
  
    session.get(url)

I get 200 as expected.

Then I send the API request

credentials = "user:password"
token = base64.b64encode(credentials.encode())

header = {"Authorization": "Basic "   token.decode('utf-8')}

response = requests.get(url=url, headers=header)

But I get error 401 in the response.

How can I do it differently to make it work?

CodePudding user response:

i have some sample of mine, i hope it'll help you:

header = {....}
data = {...}
response= requests.post(url=url, data=data,headers=header,auth=(user,password))

CodePudding user response:

as far as I know, wordpress does not even accept Authentication user/password by default.

you can only login through cookies (source)

but there is a way to authenticate rest api using user/password and that is plugins. I suggest Wordpress REST API Authentication

then usage would be so easy like :

import requests

headers = {
    'Authorization': 'Basic base64encoded <username:password>',
    'Content-Type': 'application/x-www-form-urlencoded',
}

data = 'title=sample post&status=publish'

response = requests.post('http://example.com/wp-json/wp/v2/posts', headers=headers, data=data)

CodePudding user response:

Taking from the two answers (thanks!), here is the answer that is a merge of the two.

The API authentication is sent in the header (and an API authentication plugin is needed in WP).

credentials = "user:password"
token = base64.b64encode(credentials.encode())

header = {"Authorization": "Basic "   token.decode('utf-8')}

The session authentication is sent in the auth parameter of the request

response = requests.get(url=url, headers=header, auth=('my_user', 'my_password'))
  • Related