You need to use a session object and send the authentication each request. The session will also track cookies for you:

session = requests.Session()
session.auth = (user, password)

auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')
Answer from Martijn Pieters on Stack Overflow
🌐
Requests
requests.readthedocs.io › en › latest › user › authentication
Authentication — Requests 2.33.0.dev1 documentation
Some forms of authentication will additionally add hooks to provide further functionality. Further examples can be found under the Requests organization and in the auth.py file. Requests is an elegant and simple HTTP library for Python, built for human beings.
🌐
Python-requests
docs.python-requests.org › en › latest › user › authentication
Authentication — Requests 2.33.0 documentation
The __call__ method must therefore do whatever is required to make the authentication work. Some forms of authentication will additionally add hooks to provide further functionality. Further examples can be found under the Requests organization and in the auth.py file.
🌐
GeeksforGeeks
geeksforgeeks.org › python › authentication-using-python-requests
Authentication using Python requests - GeeksforGeeks
July 12, 2025 - To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server. Example - Python3 1== # import requests module import requests from requests.auth import HTTPBasicAuth # Making a get request response = requests.get('https://api.github.com/ / user, ', auth = HTTPBasicAuth('user', 'pass')) # print request object print(response) Replace "user" and "pass" with your username and password.
Top answer
1 of 2
1

I don't know if this works for your case, but I did use Basic authentication a while ago to authenticate with the Reddit API.

Here's my code:

import requests

client_auth = requests.auth.HTTPBasicAuth("put something here","put something here")

headers = {"User-Agent": "manage your reddit easily by u/0xff"}

code = "ajkldjfalkdjflajfd;lakdjfa"

data = {
    "code":code,
    "grant_type":"authorization_code",
    "redirect_uri":"http://127.0.0.1:3000/authorize_callback"
}

r = requests.post("https://www.reddit.com/api/v1/access_token", auth=client_auth, data=data, headers=headers);

print(r.content)

Just make the appropriate changes for your case and try it.

2 of 2
0

You are setting authorization information twice, and different HTTP libraries will handle this conflict in different ways.

HTTP Basic Authorization uses the Authorization header, encoding the username and password (separated by :) as base64 and setting the header to the value Basic plus space plus the base64 encoded string. You are telling both POSTman and requests to set the Authorization header to the string Basic Token and to use a username and password for Basic Auth, so the clients will have to make a choice between these two options.

Trying this out in requests version 2.25.1 I see that the auth information will win here:

>>> from requests import Session, Request
>>> from requests.auth import HTTPBasicAuth
>>> req = Request(
...     "PUT",
...     "http://example.com",
...     headers={
...         'Authorization': 'Basic Token',
...         'Content-Type': 'application/json'
...     },
...     auth=HTTPBasicAuth('login','password'),
...     data=b"{}"
... )
>>> session = Session()
>>> prepped = session.prepare_request(req)
>>> from pprint import pp
>>> pp(dict(prepped.headers))
{'User-Agent': 'python-requests/2.25.1',
 'Accept-Encoding': 'gzip, deflate',
 'Accept': '*/*',
 'Connection': 'keep-alive',
 'Authorization': 'Basic bG9naW46cGFzc3dvcmQ=',
 'Content-Type': 'application/json',
 'Content-Length': '2'}

The above session creates a prepared request so I can inspect the effect of the auth argument on the headers given to the request, and as you can see the Authorization header has been set to a base64 value created from the login and password pair.

It looks like Postman will do the same, the UI even tells you so:

You didn't share any details about what web service you are using or what expectations that service has for headers or request contents. If this a OAuth2-protected service, then you should not confuse obtaining a token with using that token for subsequent requests to protected URLs. For a grant_type="password" token request, it could be that the server expects you to use the username and password in a Basic Auth header, but it may also expect you to use client_id and client_secret values for that purpose and put the username and password in the POST body. You'll need to carefully read the documentation.

Other than that, you could replace your destination URL with an online HTTP echo service such as httpbin. The URL https://httpbin.org/put will give you a JSON response with the headers that the service received as well as the body of your request.

Further things you probably should be aware of:

  • requests can encode JSON data for you if you use the json argument, and if you do, the Content-Type header is generated for you.
  • You don't need to import the HTTPBasicAuth object, as auth=(username, password) (as a tuple) works too.
🌐
PyPI
pypi.org › project › requests-auth
requests-auth · PyPI
Use requests_auth.OktaAuthorizationCode ...ver.okta-emea.com', client_id='54239d18-c68c-4c47-8bdd-ce71ea1d50cd') requests.get('https://www.example.com', auth=okta) ......
      » pip install requests-auth
    
Published   Jun 18, 2024
Version   8.0.0
🌐
datagy
datagy.io › home › python requests › authentication with python requests: a complete guide
Authentication with Python Requests: A Complete Guide • datagy
December 30, 2022 - Because the basic authentication method is used so frequently, the requests library abstracts away some of this complexity. Rather than needing to create a new HTTPBasicAuth object each time, you can simply pass a tuple containing your username and password into the auth= parameter. ... # Simplifying Basic Authentication with Python requests import requests print(requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))) # Returns: <Response [200]>
🌐
TutorialsPoint
tutorialspoint.com › home › requests › requests authentication in python
Requests Authentication in Python
March 4, 2005 - This is the simplest form of providing authentication to the server. To work with basic authentication, we are going to use HTTPBasicAuth class available with requests library. Here is a working example of how to use it.
Find elsewhere
🌐
Real Python
realpython.com › python-requests
Python's Requests Library (Guide) – Real Python
July 23, 2025 - A real-world example of an API that requires authentication is GitHub’s authenticated user API. This endpoint provides information about the authenticated user’s profile. If you try to make a request without credentials, then you’ll see that the status code is 401 Unauthorized:
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-post-request-with-basic-authentication-exampleexample.html
Python Post Request with Basic Authentication Example - ItSolutionstuff.com
October 30, 2023 - You can use these examples with python3 (Python 3) version. ... import requests import json url = 'https://reqres.in/api/users' params = {'name': 'Hardik', 'job': 'Developer'} username = "enterUsername" password = "enterPassword" response = requests.post(url, auth=(username, password), json=params) data = response.json() print(data) ... import requests import json url = 'https://reqres.in/api/users' header = {"Authorization" : "Basic cG9zdG1hbjpwYXNzd29yZA=="} response = requests.get(url, headers=header) data = response.json() print(data)
🌐
Newtum
apitest.newtum.com › examples › python-requests-with-authentication-basic-auth
Python Requests with Basic Authentication | `HTTPBasicAuth` | API Navigator
import requests from requests.auth import HTTPBasicAuth # This is a sample endpoint that requires basic auth url = 'https://httpbin.org/basic-auth/user/passwd' # Provide username and password response = requests.get(url, auth=HTTPBasicAuth('user', 'passwd')) print('Status Code:', response.statu...
🌐
Medium
medium.com › @brahmaraokothapalli › handling-basic-api-authentication-using-requests-in-python-63f11610567c
Handling basic API authentication using requests in Python | by Brahma Rao Kothapalli | Medium
October 12, 2023 - In the below example, I am trying ... should be ‘200’. import requests BASE_URI = "https://postman-echo.com/basic-auth" credentials = ('postman', 'password') # username and password as a tuple def test_basic_auth(): '''testing ...
🌐
ProxiesAPI
proxiesapi.com › articles › python-requests-library-making-authenticated-post-requests
Python Requests Library: Making Authenticated POST Requests | ProxiesAPI
Making authenticated API requests is very common. This Requests example provides a simple and Pythonic way to POST data with the required credentials.
🌐
Apidog
apidog.com › blog › python-put-request
How to make a PUT Request in Python (2026 Guide)
February 2, 2026 - Ensure your request includes these when needed. You can use the auth parameter in the requests library to provide authentication credentials. For example, you can use basic authentication with the HTTPBasicAuth ...
🌐
PythonForBeginners
pythonforbeginners.com › home › requests in python
Requests In Python - PythonForBeginners.com
August 25, 2020 - Making requests with Basic Auth is extremely simple: from requests.auth import HTTPBasicAuth requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) # Due to the prevalence of HTTP Basic Auth, # requests provides a shorthand for this authentication method: ...
🌐
ProxiesAPI
proxiesapi.com › articles › demystifying-authentication-with-python-requests
Demystifying Authentication with Python Requests | ProxiesAPI
Many modern APIs use token-based authentication. Rather than passing credentials directly, you get an access token from the API, usually via some authorization workflow. You then pass that token to authenticate. With Python Requests, you just need to add the token to the
🌐
Innovate Yourself
innovationyourself.com › http-requests-in-python
HTTP Requests in Python 3: A Comprehensive Guide to GET, PUT, POST, and DELETE – Innovate Yourself
September 5, 2023 - These practical examples illustrate how to handle authentication in POST requests, whether it’s using basic authentication with username and password or token-based authentication with an authentication token. Understanding these techniques is crucial for interacting securely with authenticated APIs. PUT ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-requests-tutorial
Python Requests - GeeksforGeeks
July 31, 2025 - import requests from requests.auth import HTTPBasicAuth response = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) print(response.status_code) ... Replace 'user' and 'pass' with your credentials (username and ...