402 Payment Required
Reserved for future use. Originally intended for digital payment systems.
Meaning & Description
Common Causes
- Account credit balance reached zero
- Monthly API request quota exceeded
- Subscription expired or payment failed
- Accessing premium features on a free tier
How to fix a 402 error
- Check the API documentation to understand the provider's billing limits.
- Verify the billing status and credit card validity in the service dashboard.
- Review the response body for links to upgrade or payment pages.
- Check if you accidentally hit a premium endpoint with a free-tier token.
Browser & SEO Behaviour
Browser Behavior
Treated as a generic 4xx error. No special built-in handling exists in modern browsers.
SEO Impact
Functions similarly to a 403 Forbidden. Search engines will not index the content and will drop the URL over time.
CDN Behavior
Not cached by default. Passed through directly to the client.
Code Examples
app.get('/api/premium-data', async (req, res) => {
const user = req.user;
if (user.apiCredits <= 0) {
return res.status(402).json({
error: 'Insufficient credits.',
upgradeUrl: 'https://example.com/billing'
});
}
user.apiCredits -= 1;
await user.save();
res.json({ data: 'Premium content' });
});from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/generate-image")
def generate_image(user_plan: str):
if user_plan == "free":
raise HTTPException(
status_code=402,
detail="Payment required to use the image generation feature."
)
return {"status": "Generating..."}func generateReport(w http.ResponseWriter, r *http.Request) {
hasPremium := checkUserSubscription(r)
if !hasPremium {
http.Error(w, "Premium subscription required", 402)
return
}
w.Write([]byte("Report Data"))
}[HttpGet("ai-completion")]
public IActionResult GetAiCompletion()
{
var account = GetAccount();
if (account.Balance < 0.01m)
{
return StatusCode(402, new { Message = "Insufficient balance for API call." });
}
return Ok(new { Result = "AI text" });
}curl -i -X POST https://api.saas.com/v1/heavy-job \
-H "Authorization: Bearer user_token"
# Returns 402 if quota is exceededRaw HTTP Response Example
HTTP/1.1 402 Payment Required
Content-Type: application/json
Content-Length: 104
{
"error": "payment_required",
"message": "You have exhausted your monthly API credits.",
"credits": 0
}Real-world Examples
Frequently Asked Questions
Why is 402 "Reserved for future use"?
It was created in the early 90s with the anticipation that digital cash and micro-payments would be built directly into the HTTP protocol. That vision never materialized, leaving the code without a strict standard.
Is it okay to use 402 in my API?
Yes, although not strictly standardized, it is widely accepted as a best practice for indicating that an account quota has been reached or a payment is due.
Should I use 402 or 429 for rate limits?
Use 429 Too Many Requests for temporary rate limiting (e.g., requests per second). Use 402 when the limit is tied to billing or subscription quotas (e.g., monthly limits).
Do browsers prompt for payment on a 402?
No, modern browsers do not have a built-in payment prompt triggered by this status code.
Can I redirect a user on 402?
If it's a web application, returning a 302 Redirect to a billing page is usually a better user experience than showing a 402 error page.
Did You Know?
The 402 status code is one of the few HTTP codes explicitly created for a feature that never actually made it into the web ecosystem (native micro-transactions).
Despite having no standard, major tech companies like Google, Stripe, and Shopify use 402 heavily for billing-related API errors.
Developer Tips
- If you return a 402, include a payload that tells the client exactly what quota was exceeded and provides a URL to resolve the billing issue.
- Use 402 specifically for hard billing limits, and stick to 429 for algorithmic rate limiting designed to protect your infrastructure.
- Always set `Cache-Control: no-cache` when returning a 402 to ensure the client immediately retries once they pay.
Interview Questions
These are questions you might face in a backend or API design interview that touch on HTTP 402.
What was the original purpose of the 402 status code?
It was designed for digital cash and micro-payments built directly into the web protocol, a concept that was never fully realized.
How would you decide between returning a 402 and a 403?
I would use 403 Forbidden for permission or role-based access denial. I would use 402 Payment Required strictly when access is denied because a financial quota was exceeded or a subscription lapsed.
When implementing an API with a monthly free tier, what status code should you return when the tier is exceeded?
402 Payment Required is the most appropriate, as it clearly signals to the developer that a billing upgrade is necessary, distinguishing it from 429 (Too Many Requests), which implies they just need to slow down.
Common Interview Mistakes
- Assuming 402 is an official standard for e-commerce transactions.
- Confusing 402 Payment Required with 429 Too Many Requests.
- Stating that browsers have built-in UI for handling 402 responses.