I'm totally beginner at Django (from a Node/Express background). I need to to make a call to an API that uses basic authorization.
To make requests i'm using the requests module but I don't know where to pass the auth headers. In Axios I normally set the default headers like this:
import axios from 'axios'
const token = `Basic ${Buffer.from(`${process.env.API_USERNAME}:${process.env.API_PASSWORD}`).toString('base64')}`;
axios.defaults.baseURL = process.env.API_URL;
axios.defaults.headers.common['Authorization'] = token;
My service in Django:
from base64 import b64encode
import requests
import environ
environ.Env.read_env()
endpoint = 'some url'
credentials = f"{env('API_USERNAME')}:{env('API_PASSWORD')}"
encodedCredentials = str(b64encode(credentials.encode("utf-8")), "utf-8")
auth = f'"Authorization": "Basic {encodedCredentials}"'
def get_api_data():
return requests.get(endpoint).json()
How should I pass the headers?
If api using token authentication you can use headers argument to pass token with request header:
return requests.get(endpoint, headers={"Authorization": f"Basic {encodedCredentials}"}).json()
Or you can pass login and password directly with auth argument:
return requests.get(endpoint, auth=("login", "password")).json()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With