0
0
Rest APIprogramming~5 mins

Basic authentication in Rest API

Choose your learning style9 modes available
Introduction

Basic authentication helps a server check who you are by asking for a username and password. It keeps things simple and quick.

When you want to protect a simple API so only certain users can access it.
When testing an API that requires a username and password.
When you need a quick way to add security without complex setup.
When building a small app where users must log in to see their data.
Syntax
Rest API
Authorization: Basic base64(username:password)

The username and password are joined by a colon and then encoded in base64.

This header is sent with each request to prove who you are.

Examples
This means username is 'user' and password is 'pass' encoded in base64.
Rest API
Authorization: Basic dXNlcjpwYXNz
Here username is 'admin' and password is '1234'.
Rest API
Authorization: Basic YWRtaW46MTIzNA==
Sample Program

This program shows how to send a request with Basic authentication. It encodes the username and password, adds them to the header, and calls a test API that requires these credentials.

Rest API
import base64
import requests

username = 'user'
password = 'pass'

# Combine username and password
user_pass = f'{username}:{password}'

# Encode to base64
encoded = base64.b64encode(user_pass.encode()).decode()

# Prepare headers with Basic Auth
headers = {'Authorization': f'Basic {encoded}'}

# Example URL (replace with real API endpoint)
url = 'https://httpbin.org/basic-auth/user/pass'

# Send GET request with headers
response = requests.get(url, headers=headers)

# Print status and response JSON
print('Status code:', response.status_code)
print('Response:', response.json())
OutputSuccess
Important Notes

Basic authentication sends credentials in base64, which is not encrypted. Use HTTPS to keep it safe.

Each request must include the Authorization header with the encoded credentials.

For better security, consider more advanced methods like token-based authentication.

Summary

Basic authentication uses a username and password encoded in base64 sent in the Authorization header.

It is simple but should be used only over secure connections (HTTPS).

It is useful for quick and easy protection of APIs or services.