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
The netrc file overrides raw HTTP authentication headers set with headers=. If credentials for the hostname are found, the request is sent with HTTP Basic Auth.
๐ŸŒ
Python-requests
docs.python-requests.org โ€บ en โ€บ latest โ€บ user โ€บ authentication
Authentication โ€” Requests 2.33.0 documentation
Many web services that require authentication accept HTTP Basic Auth. This is the simplest kind, and Requests supports it straight out of the box. Making requests with HTTP Basic Auth is very simple:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ authentication-using-python-requests
Authentication using Python requests - GeeksforGeeks
July 12, 2025 - See the requests-oauthlib OAuth2 documentation for details of the various OAuth 2 credential management flows: ... Backend Application Flow Other Authentication Requests is designed to allow other forms of authentication to be easily and quickly plugged in. Members of the open-source community frequently write authentication handlers for more complicated or less commonly-used forms of authentication.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ requests-auth
requests-auth ยท PyPI
You can use basic authentication using requests_auth.Basic.
      ยป 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 - 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 ...
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.
๐ŸŒ
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 - BASE_URI = "https://postman-echo.com/basic-auth" header ={ 'Content-Type': 'application/json', 'Authorization': 'Basic cG9zdG1hbjpwYXNzd29yZA==' } def test_basic_auth_using_token(): '''testing basic auth using ''' response = requests.get(BASE_URI, headers=header) print(response.text) status = response.status_code print(f"\nStatus Code is {status}") if status == 200: print("Authentication successful") else: print("Authentication failed")
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ home โ€บ requests โ€บ requests authentication in python
Requests Authentication in Python
March 4, 2005 - Requests library has most commonly used authentication in requests.auth, which are Basic Authentication (HTTPBasicAuth) and Digest Authentication (HTTPDigestAuth). 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.
๐ŸŒ
Python-requests
docs.python-requests.org โ€บ en โ€บ v2.2.1 โ€บ user โ€บ authentication
Authentication โ€” Requests 2.2.1 documentation
If credentials for the hostname are found, the request is sent with HTTP Basic Auth. Another very popular form of HTTP Authentication is Digest Authentication, and Requests supports this out of the box as well:
๐ŸŒ
ProxiesAPI
proxiesapi.com โ€บ articles โ€บ python-requests-library-making-authenticated-post-requests
Python Requests Library: Making Authenticated POST Requests | ProxiesAPI
The Python Requests library provides a simple way to make HTTP requests in Python, including POST requests with Basic HTTP Authentication for authenticated API requests.
๐ŸŒ
Real Python
realpython.com โ€บ python-requests
Python's Requests Library (Guide) โ€“ Real Python
July 23, 2025 - When you pass your credentials in a tuple to the auth parameter, Requests applies the credentials using HTTPโ€™s basic access authentication scheme under the hood. ... You may wonder where the string Basic dXNlcjpwYXNzd2Q= that Requests set as the value for your Authorization header comes from. In short, itโ€™s a Base64-encoded string of the username and password, prefixed with "Basic ":
๐ŸŒ
Python-requests
docs.python-requests.org โ€บ en โ€บ v1.1.0 โ€บ user โ€บ authentication
User authentication - Python Requests
Many web services that require authentication accept HTTP Basic Auth. This is the simplest kind, and Requests supports it straight out of the box. Making requests with HTTP Basic Auth is very simple:
๐ŸŒ
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.status_code) if response.status_code == 200: print('Authentication successful!') print(response.json()) else: print('Authentication failed.')CopyRun
๐ŸŒ
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
๐ŸŒ
Python-requests
docs.python-requests.org โ€บ en โ€บ latest โ€บ api
Developer Interface โ€” Requests 2.33.0.dev1 documentation
Sends a PUT request. Returns Response object. ... data โ€“ (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request. **kwargs โ€“ Optional arguments that request takes. ... When being redirected we may want to strip authentication from the request to avoid leaking credentials.
๐ŸŒ
Imperial College London
python.pages.doc.ic.ac.uk โ€บ 2021 โ€บ lessons โ€บ http โ€บ 05-advanced โ€บ 01-authentication.html
Advanced Lesson 2: HTTP Requests > Authentication
It accepts a different number of authentication protocols, including HTTP Basic Authentication by default. >>> username = "cobra" >>> password = "hiss" >>> response = requests.get("http://localhost:5000/user", auth=(username, password)) >>> print(response.status_code) 200 >>> print(response.json()) {'email': 'jar.fowler@example.com', 'id': 1, 'name': 'Jar Fowler', 'user': 'cobra'} >>> print(response.request.headers) {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Basic Y29icmE6aGlzcw=='}
๐ŸŒ
Claudia Kuenzler
claudiokuenzler.com โ€บ blog โ€บ 1180 โ€บ how-to-send-http-requests-python-authentication-json-post-data
How to send HTTP requests in Python, handle authentication and JSON POST data
February 15, 2022 - A request without a successful authentication returns a 401 response code. For a "Basic Auth" authentication, a curl request looks like this: $ curl https://www.example.com/hidden.txt -u "myuser:secret" -I HTTP/2 200 server: nginx date: Tue, 15 Feb 2022 08:36:16 GMT content-type: text/plain content-length: 187 [...] In Python, the official parameter would be auth=BasicAuth, but as Basic Auth is the most common authentication method over HTTP, a simple auth= is enough:
๐ŸŒ
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)