Real-world examples of examples of basic authentication API example

If you work with APIs long enough, you’ll eventually run into basic authentication. It’s old, simple, and still everywhere. Developers keep searching for real, working examples of examples of basic authentication API example code because docs are often vague, outdated, or skip the security caveats. This guide fixes that. We’ll walk through practical examples of how to send a basic auth header with curl, JavaScript, Python, Java, and Postman, plus what modern teams are actually doing with it in 2024–2025. Instead of toy snippets, you’ll see how basic authentication shows up in internal APIs, legacy integrations, and quick prototypes. Along the way, we’ll call out best practices, where it still makes sense, and where you should absolutely avoid it. If you want clear examples of how to build, encode, and send basic auth credentials in real requests—and understand when to move on to tokens—this is the place to start.
Written by
Jamie
Published

Fast examples of basic authentication API example in real requests

Before definitions, let’s look at how this actually appears on the wire. Every basic authentication API example revolves around a single header:

Authorization: Basic base64(username:password)

That’s it. The rest is just how you generate and attach that header.

Here are a few quick examples of examples of basic authentication API example usage that you’ll see in real life:

  • A curl call to an internal metrics API using a service account.
  • A Python script pulling nightly reports from a legacy billing system.
  • A Node.js backend talking to an old partner API that never migrated to OAuth.
  • A Postman collection used by QA to hit staging endpoints with fixed credentials.

All of these examples include the same pattern: combine username:password, Base64-encode it, and send it in the Authorization header over HTTPS.


Curl and command-line examples of basic authentication API example usage

When people ask for the simplest example of basic auth, curl is usually the answer. It’s the cleanest examples of examples of basic authentication API example pattern you can show in one line.

Curl with -u flag

curl -u "api-user:supersecret" \
  https://api.example.com/v1/customers

Curl automatically:

  • Concatenates api-user:supersecret.
  • Base64-encodes that string.
  • Sends the header:
Authorization: Basic YXBpLXVzZXI6c3VwZXJzZWNyZXQ=

You can see the actual header curl sends by adding -v:

curl -v -u "api-user:supersecret" https://api.example.com/v1/customers

This is one of the best examples for quickly verifying that a basic authentication API example in the docs actually works. If a vendor tells you “use basic auth,” this is usually the first test you run.

Curl with manual header

Sometimes you want to control the header yourself. For example, in CI logs you may not want to expose the raw username and password, but you’re okay pasting a temporary encoded string:

## Local-only example – do NOT commit this to git
curl -H "Authorization: Basic YXBpLXVzZXI6c3VwZXJzZWNyZXQ=" \
  https://api.example.com/v1/customers

This manual approach is often used in documentation as an examples of basic authentication API example snippet because it makes the header obvious.


JavaScript examples include browser and Node.js basic auth

Modern frontends rarely use basic auth directly against public APIs because you’d expose credentials in the browser. But in controlled environments—internal dashboards, local tools, or Node.js backends—you still see it.

Node.js fetch example of basic auth

import fetch from "node-fetch";

const username = process.env.API_USER;
const password = process.env.API_PASSWORD;

const token = Buffer.from(`\({username}:}\(password}`).toString("base64");

const response = await fetch("https://api.example.com/v1/orders", {
  headers: {
    "Authorization": `Basic ${token}`,
    "Accept": "application/json"
  }
});

const data = await response.json();
console.log(data);

This is a textbook examples of examples of basic authentication API example in backend JavaScript:

  • Credentials live in environment variables.
  • The Buffer API encodes username:password to Base64.
  • The Authorization header is set manually.

Browser fetch example (why it’s risky)

const username = "demo-user";
const password = "demo-pass";

const token = btoa(`\({username}:}\(password}`);

fetch("https://internal.example.com/reports", {
  headers: {
    "Authorization": `Basic ${token}`
  },
  credentials: "include"
}).then(res => res.json())
  .then(console.log)
  .catch(console.error);

This works as an example of basic auth, but it’s only acceptable for tightly controlled internal tools. Anyone with access to the browser can see the token in DevTools. That’s why most public APIs have moved to OAuth 2.0, API keys, or JWT-based schemes.

For background on why sending passwords directly is risky, it’s worth reading general security guidance from organizations like NIST or the UK National Cyber Security Centre on modern password handling.


Python and requests: the most common real examples in scripts

If you ask backend engineers for their favorite examples of basic authentication API example usage, many will show you a Python script. The requests library makes this almost boringly easy.

Python requests with built-in basic auth

import os
import requests
from requests.auth import HTTPBasicAuth

username = os.environ["API_USER"]
password = os.environ["API_PASSWORD"]

response = requests.get(
    "https://api.example.com/v1/invoices",
    auth=HTTPBasicAuth(username, password),
    timeout=10
)

response.raise_for_status()
print(response.json())

Here, requests handles the Base64 encoding and header creation. This is one of the best examples for:

  • Scheduled jobs that sync data between systems.
  • One-off migration scripts against legacy APIs.
  • Internal tooling where you control both client and server.

Python with manual header for debugging

Sometimes you want to see the exact token used in a basic authentication API example, especially when debugging failed requests:

import base64
import requests

user_pass = "api-user:supersecret".encode("utf-8")
encoded = base64.b64encode(user_pass).decode("utf-8")

headers = {
    "Authorization": f"Basic {encoded}",
    "Accept": "application/json"
}

response = requests.get("https://api.example.com/v1/customers", headers=headers)
print(response.status_code, response.text)

This pattern is handy in teaching materials when you want examples of examples of basic authentication API example that expose the encoding step explicitly.


Java and Spring: enterprise examples of basic authentication API example

In larger organizations, Java and Spring Boot still power a lot of internal APIs. Even in 2024–2025, many of those endpoints use basic authentication behind VPNs or API gateways.

Java with HttpClient

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;

public class BasicAuthExample {
    public static void main(String[] args) throws Exception {
        String username = System.getenv("API_USER");
        String password = System.getenv("API_PASSWORD");

        String auth = username + ":" + password;
        String encoded = Base64.getEncoder().encodeToString(auth.getBytes());

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.example.com/v1/users"))
                .header("Authorization", "Basic " + encoded)
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}

This is a straightforward example of basic auth in a modern Java application. In Spring, you often see the server side configured to accept it for internal tools or actuator endpoints.

Spring Security server-side basic auth

On the server, a minimal Spring Security configuration might look like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/actuator/**").authenticated()
                .anyRequest().permitAll()
            )
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf.disable());

        return http.build();
    }

    @Bean
    public UserDetailsService users() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("monitor")
            .password("monitor-pass")
            .roles("MONITOR")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

This is one of the most realistic examples of basic authentication API example usage in production: protecting actuator or admin endpoints inside a private network, often with an additional layer like a VPN or reverse proxy.


Postman and testing: the easiest examples of examples of basic authentication API example

When teams write internal documentation, their best examples often live in Postman collections. QA engineers and developers can run authenticated requests without writing code.

Here’s how a typical basic authentication setup looks in Postman:

  • In the Authorization tab, choose Basic Auth.
  • Enter username and password.
  • Postman automatically generates the Authorization: Basic … header.

You can then save that request as part of a collection and share it with the team. These are great real examples for onboarding:

  • New hires can see exactly how to hit staging APIs.
  • Support engineers can reproduce customer issues quickly.

For teaching purposes, many API tutorials use screenshots of Postman as examples of basic authentication API example configurations because the UI makes the concept concrete.


Where basic authentication still shows up in 2024–2025

Despite the rise of OAuth 2.0 and OpenID Connect, basic auth has not disappeared. In 2024–2025 you still see it in several patterns:

  • Internal microservices behind a gateway where TLS termination and access control live at the edge.
  • Legacy vendor APIs that haven’t been modernized but are too expensive to replace.
  • Automation scripts for data exports, backups, and one-off integrations.
  • Admin and health endpoints (for example, /health or /metrics) that sit behind both network controls and basic auth.

Security guidance from organizations like CISA and NIST consistently recommends minimizing password-based mechanisms where possible, but they also recognize that legacy patterns persist. That’s why good examples of examples of basic authentication API example usage always emphasize:

  • HTTPS is non‑negotiable.
  • Credentials must be stored outside source code.
  • Rotation and auditing are as important as the header format.

Better patterns that still feel similar to basic auth

If you understand basic auth, you’re already halfway to understanding more modern schemes. Some of the best examples of migration paths include:

  • API keys in headers – similar to basic auth, but you send a single token instead of username:password.
  • Bearer tokens (JWTs) – the header looks like Authorization: Bearer <token> instead of Basic <token>.
  • Mutual TLS – the client proves its identity with a certificate instead of a password.

In many organizations, the first step away from a basic authentication API example is to wrap it with an API gateway that handles OAuth or API keys at the edge while the backend still expects basic auth internally. That way, external clients never see the old pattern, but you don’t have to rewrite every service overnight.


FAQ: common questions about examples of basic authentication API example

What are some real examples of basic authentication in APIs?

Real examples include:

  • A Python script using requests with HTTPBasicAuth to pull invoices from a billing API.
  • A curl command with -u user:pass hitting an internal monitoring endpoint.
  • A Node.js backend using Buffer.from('user:pass').toString('base64') to call a partner API.
  • A Postman collection where the Authorization tab is set to Basic Auth for staging endpoints.

These are all practical examples of examples of basic authentication API example usage that you’ll find in day‑to‑day engineering work.

Is basic authentication safe to use in 2025?

It can be acceptable in limited scenarios if:

  • You always use HTTPS.
  • Credentials are stored securely (for example, environment variables or a secrets manager).
  • Access is restricted by network controls (VPN, private subnets, gateways).

For public APIs, it’s usually better to follow more modern guidance like OAuth 2.0 and token-based schemes, as discussed in resources from organizations such as NIST and similar security standards bodies.

How do I test a basic authentication API example quickly?

The fastest way is usually:

curl -v -u "user:password" https://api.example.com/resource

If that works, you can translate it into Python, JavaScript, Java, or Postman. Many docs even provide examples of basic authentication API example requests in curl specifically because it’s so easy to copy, paste, and debug.

What is the difference between basic auth and bearer tokens?

With basic auth, you send a Base64‑encoded username:password on every request. With bearer tokens, you send a single token (often a JWT) that represents an authenticated session or client. The header format is different:

  • Basic: Authorization: Basic <base64(username:password)>
  • Bearer: Authorization: Bearer <token>

Modern API security patterns strongly prefer bearer tokens, but examples of examples of basic authentication API example code remain useful for quick tests, internal tools, and understanding the foundations of HTTP auth.


In short, the best examples of basic authentication API example usage in 2024–2025 are no longer about public consumer apps. They live in scripts, admin tools, and legacy integrations. If you treat them as a stepping stone toward more advanced auth—and not the final destination—you’ll be using them the way modern teams do.

Explore More Authentication Methods in APIs

Discover more examples and insights in this category.

View All Authentication Methods in APIs