Skip to content

By the Octri team · Updated

401 Unauthorized

Share

A 401 means the request didn’t carry valid credentials. The name says unauthorized, but it’s about authentication, meaning the server doesn’t know who’s calling. Sending working credentials should fix it.

All HTTP status codes

Class
4xx client error
Defined in
RFC 9110, section 15.5.2
Retry
After new credentials
Key header
WWW-Authenticate
Cacheable by default
No

When your API should return 401

Return 401 when the API key or token is missing, expired, revoked or malformed. RFC 9110 says a 401 must include a WWW-Authenticate header naming the scheme, like Bearer realm="api", and for OAuth tokens RFC 6750 adds an error value such as invalid_token.

If you know who’s calling and they aren’t allowed to do this, that’s a 403. The test is whether new credentials could help. An expired token gets a 401, and a valid key on the wrong plan gets a 403. Where hiding that a resource exists matters more, a 404 is allowed too.

How public APIs declare 401 in their OpenAPI specs

Six of the eleven public specs we score declare a 401, as they were on 4 December 2026. Asana does on 301 operations, GitHub on 203 and OpenAI on 64.

Only one of those 614 declarations documents WWW-Authenticate, on OpenAI, although RFC 9110 requires the header on every 401.

APIOperationsDeclare 401With WWW-AuthenticateHow errors are described
Asana3023010Per status code
GitHub1,2882030Per status code
OpenAI406641Per status code
Box297230Per status code, plus a default
Adyen Checkout28200Per status code
SendGrid Mail330Per status code
Stripe61200One default error response
Plaid35100One default error response
Twilio19700No error responses
Slack17400One default error response
Swagger Petstore1900Per status code, plus a default

Counted per operation from each vendor’s public OpenAPI document on 4 December 2026.

Declare 401 in your OpenAPI spec

Declare the 401 once with its WWW-Authenticate header and reference it from every operation that needs credentials. The securitySchemes entry beside it tells generators how to send the key.

yaml
paths:
  /invoices:
    get:
      operationId: listInvoices
      security:
        - bearerAuth: []
      responses:
        "200":
          $ref: "#/components/responses/InvoiceList"
        "401":
          $ref: "#/components/responses/Unauthorized"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
  responses:
    Unauthorized:
      description: Missing, expired or invalid credentials.
      headers:
        WWW-Authenticate:
          schema:
            type: string
          example: Bearer realm="api", error="invalid_token"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"

What an Octri SDK does with a 401

An Octri SDK doesn’t retry a 401, because the same credentials will fail again. The caller gets an SdkUnauthorizedError with the status, the headers and the request ID, in TypeScript, Python, Java, Kotlin, PHP and Ruby.

For OAuth client credentials, the TypeScript SDK caches the token and fetches a new one 30 seconds before it expires, so a long-running process doesn’t start getting 401s when the token runs out. Concurrent requests that find it expired share one refresh.

typescript
import { Acme, SdkUnauthorizedError } from "acme-sdk";

const acme = new Acme({ apiKey: process.env.ACME_API_KEY });

try {
  await acme.invoices.list();
} catch (err) {
  if (err instanceof SdkUnauthorizedError) {
    // Not retried. The header names the scheme and why the key failed.
    console.log(err.headers["www-authenticate"], err.requestId);
  }
  throw err;
}

More on retries and typed errors in SDK error handling.

Catch a wave of 401s after a release

A single 401 is usually one developer with an old key. Hundreds in an hour on the same SDK release usually means something changed on your side, like a rotated signing key or a new token audience.

An Octri SDK with monitoring switched on reports each 401 to Octri Monitoring with the operation, the request ID and the SDK release when one is set. Search by release to see whether one version is failing, and set a threshold alert so the spike reaches you before the support tickets do.

Monitoring is off in the SDK until the developer using it turns it on, so the count covers the users who did.

sql
statusCode = 401 AND release = '2.4.0'
  ORDER BY timestamp DESC LIMIT 50

HTTP 401 questions

Should a 401 say why the credentials failed?

Partly. Say whether the token is missing, expired or malformed, since that tells the developer what to fix. Don’t say whether a username exists, because that helps an attacker guess accounts.

Is it safe to return 401 for a resource that doesn’t exist?

Yes. Checking credentials before looking up the resource means an anonymous caller can’t learn which IDs exist, and it’s the order most frameworks run in anyway.

Does a browser show a login box on a 401?

Yes, if the WWW-Authenticate header names the Basic scheme. APIs that use Bearer tokens don’t trigger it, which is one reason JSON APIs rarely use Basic.

Share