Skip to content

API Security Best Practices

A practical guide to API security: authentication, authorization, rate limiting, input validation, and the design habits that keep your endpoints from leaking.

Wahid IqbalBy , Head of ComplianceUpdated 8 min read

API Penetration Testing ServicesFrom $4,000Fixed scope, free retest, no hourly billing.

Get my fixed price

API security best practices come down to eight habits: authenticate every caller, authorize every object and function, validate every input, limit consumption, harden the transport and configuration, keep an inventory of what you expose, log and monitor for abuse, and secure webhooks and third-party calls.

APIs are where modern applications keep their doors. They expose data and operations directly, often to clients you do not control, which makes them one of the highest-value targets an attacker can find. The good news is that most API breaches trace back to a short list of well-understood failures. The OWASP API Security Top 10 (2023 edition) names them, and four of its ten entries are authentication or authorization failures. Get the fundamentals right and you remove the risks that list ranks highest. Here are the practices that matter most, and the reasoning behind each.

Authentication: prove who is calling

Every non-public endpoint must verify the caller’s identity, and it has to do so on every request. Most token-based APIs are stateless: there is no server-side session, so each call must carry proof of identity that the server validates independently. APIs that use cookie sessions need the same check on every request, plus protection against cross-site request forgery.

  • Use a proven standard such as OAuth 2.0 with properly validated tokens, rather than inventing your own scheme. The OAuth 2.0 security best current practice (RFC 9700) sets the baseline: PKCE for public clients, exact redirect URI matching, and no implicit grant.
  • If you issue JSON Web Tokens (JWTs), follow RFC 8725: accept only the signing algorithms you expect and never none, and check the signature, issuer, audience and expiry on every request.
  • Give tokens sensible expiration and support revocation, so a leaked token does not grant permanent access. Access tokens should live for minutes, not days.
  • For service-to-service calls, mutual TLS or another sender-constrained token stops a stolen token being replayed from somewhere else.
  • Never place API keys or tokens in URLs, where they leak into logs, browser history, and referrer headers. Use headers.
  • Treat authentication endpoints as prime targets and rate-limit them aggressively against brute force.

Authorization: enforce what they can do, on every object

Authentication is who you are; authorization is what you may touch. This is where the most damaging API flaws live, so treat it as the center of your security effort.

The dominant API vulnerability is broken object-level authorization: the API checks that you are logged in, but not that this record belongs to you. An attacker changes an ID in the request and reads someone else’s data (our guide has IDOR examples and fixes). Defend against it directly:

  • On every request that references an object, verify that the authenticated caller is actually permitted to access that specific object. Never trust an ID from the client as proof of ownership.
  • Enforce function-level authorization too: hiding an admin endpoint is not protecting it. Check the caller’s privilege on the server, every time.
  • Apply least privilege. Tokens and keys should carry the minimum scope the task requires, nothing more.

Validate every input

An API cannot trust anything a client sends, because a client can be anyone. Validate rigorously, as part of your wider secure coding practices:

  • Enforce a schema (expected types, formats, and ranges) and reject anything that does not conform.
  • Validate on the server without exception. Client-side checks are a UX nicety, not a security control, because the client can be bypassed entirely.
  • Use parameterized queries and safe data handling to shut down injection.
  • If the API accepts XML or SOAP, disable external entities in the parser to prevent XML external entity injection.
  • Return only the fields the caller needs. Do not ship the whole object and rely on the client to hide the rest; the extra fields are one intercepting proxy away.

Limit consumption

Without limits, an API is an open invitation to abuse. Rate limiting and throttling protect against brute-force attacks, credential stuffing, enumeration, denial of service, and runaway cost. Apply sensible per-client limits everywhere, and tighter ones on expensive or sensitive operations like authentication and search. As a starting policy, set a general limit sized to normal use (for example 100 requests a minute per client), a far tighter one on login and password reset (for example 5 attempts a minute per account and per IP address), caps on page size and payload size, and an HTTP 429 response with a Retry-After header when a limit is hit. GraphQL APIs need query depth and complexity limits as well, because one request can carry many operations; our guide to GraphQL security testing covers batching and alias abuse.

Secure the transport and the configuration

The surrounding hygiene matters as much as the code:

  • Require TLS for everything. An API serving sensitive data over plaintext is exposed by default.
  • Configure CORS deliberately, granting access only to the origins that genuinely need it rather than allowing all. List exact origins, and never reflect the request’s Origin header back or pair a wildcard with credentials.
  • Return errors that help legitimate developers without handing attackers stack traces or internal detail.
  • Set the security headers appropriate to how the API is consumed. For a JSON API, the OWASP REST Security Cheat Sheet recommends Cache-Control: no-store, a Content-Type that matches the body, X-Content-Type-Options: nosniff, Strict-Transport-Security, and Content-Security-Policy: frame-ancestors 'none'.

Know your inventory

You cannot protect endpoints you have forgotten. “Shadow” and “zombie” APIs (undocumented, deprecated, or superseded endpoints still quietly serving traffic) are a favorite target precisely because no one is watching them.

  • Maintain a current inventory of every API and version you expose.
  • Retire deprecated versions rather than leaving them running unmaintained.
  • Keep your API specification accurate; it is both a development aid and a security control.

Log and monitor API abuse

Log authentication failures, authorization denials, rate-limit hits and validation errors with the caller’s identity, and never log tokens or keys. Alert on the patterns that mean abuse: one client walking through sequential object IDs, a burst of 401 or 403 responses, or a token used from two places at once.

Secure webhooks and third-party API calls

Verify the signature and timestamp on every incoming webhook and reject replays. Treat responses from third-party APIs as untrusted input. Keep API keys and signing secrets in a secrets manager, out of code, and rotate them on a schedule.

API security best practices checklist

Each practice maps to a category in the OWASP API Security Top 10 2023, and each has a direct test.

What to configure OWASP category How a tester checks it
Validated tokens on every call, short expiry, revocation API2 Broken Authentication Replays expired, altered and unsigned tokens
Ownership check on each object ID API1 Broken Object Level Authorization Requests one user’s object with another user’s token
Allowlist of readable and writable fields API3 Broken Object Property Level Authorization Adds fields such as role to an update
Server-side role check on each endpoint API5 Broken Function Level Authorization Calls admin endpoints as a normal user
Rate limits, size caps, 429 responses API4 Unrestricted Resource Consumption Sends bursts and oversized requests
Per-user limits on purchase and signup flows API6 Unrestricted Access to Sensitive Business Flows Automates the flow at volume
Allowlist for server-side fetches API7 Server Side Request Forgery Supplies internal addresses as URLs
TLS, exact CORS origins, generic errors, headers API8 Security Misconfiguration Reviews headers, CORS and errors
Accurate specification, old versions retired API9 Improper Inventory Management Looks for undocumented endpoints
Upstream responses treated as untrusted API10 Unsafe Consumption of APIs Reviews how upstream data is used

Verify with testing

Best practices reduce risk; testing confirms it. Automated scanning catches configuration and known-pattern issues, but the highest-impact API flaws (broken object-level authorization, business-logic abuse, subtle privilege gaps) require a human who understands what the API is meant to allow and probes what it actually allows. That is the core of a dedicated API penetration test. Our API pentesting checklist lists the test to run for each OWASP API Top 10 category, so you can see what a tester will try against your endpoints. If you are choosing a provider, we also compare API penetration testing companies.

None of this is exotic. It is discipline applied consistently: authenticate every caller, authorize every object, validate every input, limit every client, harden the transport and configuration, watch the logs for abuse, verify webhooks and third-party responses, and never lose track of what you have exposed. Do those well and you have closed the doors most attackers walk through. APIs rarely live alone, either. They deserve a place in your broader web application security testing program, and an API that serves a mobile app should be tested with it through mobile application penetration testing. To confirm yours are actually shut, scope an API assessment against your real endpoints. Our API pentest pricing starts at $4,000, fixed before testing, with a free retest.

Frequently asked questions

What is the most common API security vulnerability?

Broken object level authorization, first on the OWASP API Security Top 10 in both 2019 and 2023. The API confirms the caller is logged in but not that the requested record belongs to them.

Is an API gateway enough to secure an API?

No. A gateway handles authentication, rate limiting and TLS, but it cannot know which user owns which record. Object and function level authorization has to be enforced in the application behind it.

How often should an API be penetration tested?

At least once a year, and again when a major version ships, new endpoints are added or the authentication or tenant model changes.

Wahid Iqbal

Written by

Wahid Iqbal, Head of Compliance

20+ years in the field. Focus: PCI DSS, ISO 27001 & ISO 22301. Part of the team that scopes, tests, and reports for our clients. Full profile →

All articlesApplication Pentesting

Find out what an attacker sees.

Tell us what to test and see your fixed price.

Prefer the full scoping questionnaire? 
Start the conversation

Get a quick proposal

We are online