Learning |
API Security

API Security Best Practices: 27 Controls Across 5 Layers

What Is API Security?

APIs enable data exchange and functionality between different systems, applications, and services, making them a critical attack surface in modern software architectures. API security requires a multi-layered approach that spans across traffic management, strict access controls, and strict payload data hygiene. Relying on a single line of defense leaves modern applications highly exposed.

Here is a comprehensive breakdown of the core API security best practices, organized by tactical layers.

API discovery and attack surface management:

  • Continuously discover all APIs: Automatically detect new and changed API endpoints across production, cloud, on-premises, and development environments.
  • Maintain an accurate API inventory: Track each API’s endpoints, owner, exposure, data types, dependencies, and lifecycle status.
  • Identify shadow, zombie, and unmanaged APIs: Find undocumented, deprecated, and ungoverned endpoints and secure or retire them.
  • Classify APIs and sensitive data: Categorize APIs by exposure, business criticality, and the sensitivity of the data they process.
  • Assess API risk and security posture: Continuously evaluate APIs for vulnerabilities, misconfigurations, excessive exposure, and weak controls.

Traffic management and edge security:

  • Enforce TLS 1.2 or higher: Encrypt API traffic with modern TLS and disable obsolete protocols and weak cipher suites.
  • Implement HSTS: Require supported clients to use HTTPS and prevent connections from being downgraded to insecure HTTP.
  • Centralize security controls at the API edge: Apply authentication, authorization, validation, logging, and traffic controls consistently at gateways or ingress points.
  • Apply rate limiting and throttling: Restrict request volumes by client, identity, or API to reduce abuse and protect backend capacity.
  • Protect against DDoS and automated abuse: Use traffic filtering, behavioral analysis, bot controls, and DDoS mitigation to block malicious automation and traffic floods.

Authentication and authorization:

  • Adopt OAuth 2.0 and OpenID Connect: Use standardized protocols for delegated API authorization and identity-based authentication.
  • Use short-lived tokens: Limit access-token lifetimes and securely rotate or revoke refresh tokens to reduce credential exposure.
  • Enforce granular access control: Authorize every request according to the caller, operation, resource, and relevant context.
  • Validate object-level authorization: Verify that callers are permitted to access or modify each requested object, not merely the endpoint.
  • Apply the principle of least privilege: Give users and services only the API permissions required for their tasks.
  • Secure and rotate API credentials: Store credentials in secrets managers and regularly rotate or revoke keys, secrets, and signing credentials.

Payload and data security:

  • Validate requests against API schemas: Reject requests that violate expected field types, formats, structures, values, or size constraints.
  • Sanitize and normalize inputs: Normalize untrusted input and use context-appropriate protections to prevent injection and parsing attacks.
  • Minimize sensitive data exposure: Return, process, log, and retain only the sensitive information required for each API operation.
  • Detect and protect sensitive data: Continuously identify sensitive fields and apply encryption, masking, tokenization, and access controls.
  • Sanitize API error messages: Return safe errors without exposing stack traces, internal infrastructure, secrets, or implementation details.
  • Limit unexpected or oversized payloads: Enforce limits on request sizes, fields, nesting, collections, file uploads, and supported content types.

API governance, testing, and remediation:

  • Continuously assess API security posture: Monitor APIs for control gaps, configuration drift, new exposures, and policy violations throughout their lifecycle.
  • Test APIs for vulnerabilities and misconfigurations: Combine automated testing, code review, and penetration testing to identify exploitable weaknesses.
  • Prioritize risks based on severity and exposure: Rank remediation using vulnerability severity, exploitability, data sensitivity, internet exposure, and business impact.
  • Keep APIs and dependencies patched: Monitor frameworks, libraries, gateways, and runtimes for vulnerabilities and apply security updates promptly.
  • Manage API versions and retire deprecated endpoints: Track API versions, define retirement dates, migrate clients, and disable obsolete endpoints completely.

The Complete API Security Best Practices

API Discovery and Attack Surface Management

1. Continuously Discover All APIs

Continuous API discovery is essential because organizations often have APIs deployed across multiple environments, including cloud, on-premises, and partner integrations. Without ongoing discovery, undocumented or forgotten APIs can introduce significant risks, as attackers frequently exploit these overlooked interfaces. Automated discovery tools can scan:

  • Traffic
  • Code repositories
  • Infrastructure

This helps identify every API in use, providing visibility into both public and internal endpoints.

By making continuous API discovery a standard practice, organizations ensure that their security teams are aware of every interface that could be targeted. This comprehensive visibility helps prioritize protection efforts and supports compliance requirements. It also reduces the risk of “shadow APIs,” which are undocumented or unofficial endpoints that can be easily exploited if left unmanaged.

2. Maintain an Accurate API Inventory

An accurate, up-to-date API inventory is important for effective security management. This inventory should catalog all APIs, including their:

  • Endpoints
  • Owners
  • Data types handled
  • Associated risks

Without this level of detail, it’s impossible to systematically apply security controls or respond quickly to incidents involving specific APIs. Inventory management tools can automatically update records as new APIs are created or existing ones are modified, reducing manual effort and human error.

Maintaining an accurate inventory also enables better coordination across development, security, and operations teams. It ensures that teams have the context needed to assess exposure, understand dependencies, and prioritize patching or remediation. With a living inventory, organizations can more easily meet regulatory requirements and demonstrate due diligence in protecting digital assets.

3. Identify Shadow, Zombie, and Unmanaged APIs

Shadow APIs are those developed outside official processes or without formal documentation, while zombie APIs refer to deprecated or forgotten endpoints that are still accessible. Unmanaged APIs lack proper security oversight, making all three categories significant risks to the organization. Attackers often target these APIs because they typically escape routine security checks and monitoring, increasing the likelihood of vulnerabilities.

Detecting these APIs requires:

  • Active scanning
  • Monitoring network traffic
  • Reviewing code repositories for undocumented endpoints

Once identified, organizations should assess the necessity and security posture of each API, decommissioning those that are obsolete or redundant. For necessary APIs, integrating them into the official inventory and subjecting them to the same security controls as managed APIs helps reduce the attack surface and prevent unauthorized access.

4. Classify APIs and Sensitive Data

API classification involves categorizing APIs based on their business criticality, exposure (public, private, partner), and the sensitivity of the data they process. This enables organizations to apply security controls proportionate to the risk each API presents. For example, APIs handling personal or financial data require stricter access controls and monitoring compared to those serving non-sensitive information.

Classifying sensitive data within APIs is equally important, as it helps define where measures are needed, such as:

  • Encryption
  • Masking
  • Data loss prevention mechanisms

By mapping data flows and understanding how sensitive information moves through APIs, organizations can implement targeted safeguards and more easily comply with privacy regulations such as GDPR or HIPAA. This classification also supports efficient incident response and risk management.

Related content: Read our guide to API compliance.

5. Assess API Risk and Security Posture

Assessing the risk and security posture of APIs involves evaluating each interface for vulnerabilities, misconfigurations, and potential business impact if compromised. Regular risk assessments help prioritize remediation efforts and ensure that resources are focused on the most critical exposures. This process typically includes:

  • Automated vulnerability scanning
  • Manual reviews
  • Penetration testing

These help to uncover weaknesses in authentication, authorization, and data handling. A clear understanding of API risk also aids in aligning security investments with business priorities. By quantifying the potential impact of API-related incidents, organizations can justify the need for controls and allocate resources more effectively.

Traffic Management and Edge Security

6. Enforce TLS 1.2 or Higher

Transport Layer Security (TLS) is the standard protocol for securing data in transit between clients and APIs. Enforcing TLS 1.2 or higher ensures that all communications are encrypted using strong, up-to-date cryptographic algorithms, protecting against:

  • Eavesdropping
  • Man-in-the-middle attacks

Outdated protocols like SSL or early TLS versions have known vulnerabilities that can be exploited to intercept or tamper with sensitive data. Organizations should configure their API gateways and servers to reject connections using obsolete protocols and regularly review their cipher suite configurations to eliminate weak options.

Enforcing modern TLS protects data integrity and confidentiality and also helps meet compliance requirements for data protection and privacy. Regularly renewing and managing digital certificates is also critical to maintaining secure API endpoints.

7. Implement HSTS

HTTP Strict Transport Security (HSTS) is a web security policy mechanism that instructs browsers and clients to only interact with APIs over secure HTTPS connections. By implementing HSTS, organizations prevent downgrade attacks and accidental exposure of sensitive data via insecure HTTP. HSTS is enforced by sending a response header that tells clients to refuse any future attempts to connect over plain HTTP.

Enabling HSTS across all API endpoints ensures that even if a user or system attempts to connect insecurely, the connection may be:

  • Blocked
  • Automatically redirected to HTTPS

This reduces the risk of session hijacking and other man-in-the-middle attacks that target unencrypted traffic. HSTS deployment should be validated regularly to confirm that all subdomains and endpoints are covered by the policy.

8. Centralize Security Controls at the API Edge

Centralizing security controls at the API edge (typically at the API gateway or ingress point) allows organizations to enforce consistent protections before requests reach backend services. This includes:

  • Authentication
  • Authorization
  • Input validation
  • Rate limiting

Centralization reduces the risk of configuration drift and ensures that even legacy or less secure backend systems benefit from a robust security posture. API gateways can also provide logging, monitoring, and anomaly detection capabilities, giving security teams visibility into traffic patterns and potential attacks.

By managing security at the edge, organizations simplify policy updates and incident response, as changes can be applied universally without modifying each backend service individually. This approach is essential for scaling security across large or complex API ecosystems.

9. Apply Rate Limiting and Throttling

Rate limiting restricts the number of requests a client can make to an API within a specified time frame, while throttling manages the flow of requests to prevent overloading backend systems. These controls are critical for protecting APIs from abuse, such as:

  • Brute-force attacks
  • Scraping
  • Accidental traffic spikes

Implementing rate limits helps maintain service availability and ensures fair usage among clients. Effective rate limiting requires understanding normal usage patterns and setting thresholds that balance user experience with security. Granular policies can be applied per user, IP address, or API key to accommodate different client needs.

10. Protect Against DDoS and Automated Abuse

Distributed Denial-of-Service (DDoS) attacks and automated abuse can disrupt API availability and degrade service performance. Protection mechanisms include:

  • Traffic filtering
  • IP reputation checks
  • Web application firewalls (WAFs)
  • Dedicated DDoS mitigation services

These solutions identify and block malicious or excessive traffic before it reaches API infrastructure. Layered defenses are essential for handling different attack vectors, such as volumetric floods, protocol abuse, or application-layer attacks. Automated abuse detection, such as bot mitigation and behavioral analysis, helps distinguish between legitimate users and malicious automation.

Authentication and Authorization

11. Adopt OAuth 2.0 and OpenID Connect

OAuth 2.0 and OpenID Connect are industry standards for securing API access and enabling delegated authorization:

  • OAuth 2.0: Allows users to grant third-party applications limited access to resources without sharing credentials.
  • OpenID Connect: Adds an identity layer on top of OAuth, enabling authentication and user profile information exchange.

Together, they provide a flexible framework for managing secure, federated access to APIs. Implementing these protocols ensures that only authorized users and applications can access sensitive data or perform privileged operations. They support token-based authentication, scopes, and consent flows that align with modern security and privacy requirements.

12. Use Short-Lived Tokens

Short-lived access tokens reduce the time an attacker can use a token if it is stolen or exposed. APIs should issue tokens with expiration periods appropriate to the sensitivity of the operation and avoid long-lived bearer tokens wherever possible. Token expiration should always be validated server-side, along with the token’s:

  • Issuer
  • Audience
  • Signature
  • Other required claims

When longer sessions are required, use refresh tokens to obtain new access tokens without repeatedly requesting user credentials. Refresh tokens should be stored securely, rotated after use where practical, and revoked when compromise is suspected or a session ends. This limits the impact of credential theft while preserving usability for legitimate clients.

13. Enforce Granular Access Control

API authorization should control access at the level of resources, operations, and data rather than relying only on broad roles. Scopes, roles, attributes, or policy-based controls can determine whether a caller may read, create, modify, or delete a particular resource. Sensitive administrative actions should require stronger permissions than routine operations.

Authorization checks should be enforced server-side on every request and should not depend on restrictions implemented only in the client. Policies should also account for the following elements when relevant:

  • Tenant boundaries
  • Resource ownership
  • Contextual factors

Centralized policy management can help keep authorization rules consistent across services while still allowing APIs to enforce resource-specific decisions.

14. Validate Object-Level Authorization

Object-level authorization verifies that an authenticated caller is permitted to access the object identified in a request. APIs that accept identifiers such as /users/123 or /orders/456 must not assume that authentication alone grants access to those records. Otherwise, attackers may change an identifier to retrieve or modify another user’s data.

Each request should verify the caller’s relationship to the requested object before returning data or performing an operation. These checks should cover direct identifiers as well as:

  • Nested resources
  • Query parameters
  • Request bodies

Automated tests should include attempts to access objects owned by other users or tenants to detect broken object-level authorization.

15. Apply the Principle of Least Privilege

The principle of least privilege requires users, applications, and services to receive only the permissions needed to perform their intended tasks. API clients should use narrowly defined scopes and roles instead of broad administrative permissions. Service accounts should likewise be restricted to the endpoints, operations, and resources required by their workloads.

Permissions should be reviewed regularly because responsibilities and application dependencies change over time. The following should be removed promptly:

  • Unused privileges
  • Obsolete roles
  • Unnecessary service access

Combining least privilege with time-limited permissions for sensitive operations further reduces the damage possible from compromised accounts, tokens, or services.

16. Secure and Rotate API Credentials

API keys, client secrets, signing keys, and other credentials should be stored in dedicated secret-management systems rather than source code, configuration files, container images, or logs. Credentials should also be transmitted only over encrypted connections and should never be exposed in URLs, where they can leak through logs, browser history, or monitoring systems.

Organizations should rotate credentials on a defined schedule and immediately after suspected exposure. Rotation procedures should support replacing credentials without unnecessary downtime, such as by temporarily accepting both old and new credentials during migration. Monitoring credential use can also reveal:

  • Unexpected locations
  • Unusual request patterns
  • Other signs that a secret has been compromised

Payload and Data Security

17. Validate Requests Against API Schemas

API requests should be validated against a defined schema before application logic processes them. Specifications such as OpenAPI or JSON Schema can define:

  • Required fields
  • Data types
  • Formats
  • Allowed values
  • Structural constraints

Requests that do not conform to the expected contract should be rejected early. Schema validation reduces the attack surface by preventing malformed or unexpected data from reaching backend services. Validation should cover request bodies, headers, path parameters, and query parameters where applicable. Schemas should also reject unknown fields when the API does not explicitly support them, helping prevent mass assignment and similar attacks.

18. Sanitize and Normalize Inputs

APIs should treat all client-supplied input as untrusted, including:

  • Headers
  • Parameters
  • Uploaded files
  • Request bodies

Inputs should be normalized into a consistent representation before validation and processing. This prevents attackers from using alternative encodings, unusual character representations, or ambiguous formats to bypass security checks.

Sanitization should be appropriate to how the data will be used. For example, database operations should use parameterized queries rather than relying on string filtering to prevent injection. Applications generating HTML, shell commands, or other structured output should use context-specific encoding or safe APIs to prevent untrusted input from becoming executable content.

19. Minimize Sensitive Data Exposure

APIs should return only the data required for a client operation. When clients need only a subset of fields, responses should avoid exposing sensitive information such as:

  • Internal identifiers
  • Credentials
  • Personal information
  • Security metadata
  • Complete database objects

Explicit response models or allowlists can help prevent unintended fields from appearing in API responses. Sensitive data should also be minimized in requests, logs, caches, and analytics systems. When sensitive values are necessary, masking, tokenization, or encryption can reduce exposure. Data retention policies should remove information when it is no longer needed, limiting the impact of both API compromise and downstream data leaks.

20. Detect and Protect Sensitive Data

Organizations should identify which API fields contain sensitive information, such as:

  • Credentials
  • Payment data
  • Personal information
  • Health records

Data classification and automated discovery tools can help locate sensitive fields across API traffic and schemas, including fields that developers may not have documented correctly.

Once identified, sensitive data should receive controls appropriate to its classification. These can include encryption in transit and at rest, masking in logs, tokenization, access restrictions, and monitoring for unauthorized disclosure. Detection should be continuous because API schemas and payloads change as applications evolve.

21. Sanitize API Error Messages

API error responses should provide enough information for clients to handle failures without revealing implementation details. Responses should not expose:

  • Stack traces
  • Database queries
  • Filesystem paths
  • Internal hostnames
  • Secrets
  • Detailed authentication logic

Such information can help attackers understand the environment and develop more targeted attacks. Use consistent error structures with appropriate HTTP status codes and safe, predefined messages. Detailed diagnostic information can be recorded in protected server-side logs and correlated with a request or error identifier. This preserves information needed for troubleshooting without exposing sensitive details to API consumers.

22. Limit Unexpected or Oversized Payloads

APIs should enforce limits on:

  • Request size
  • Field length
  • Collection size
  • Nesting depth
  • File uploads

Without these controls, attackers can submit excessively large or complex payloads that consume memory, CPU, storage, or parser resources. This can cause denial-of-service conditions even when request rate limits are in place.

Reject unsupported content types, unexpected fields, and payload structures that exceed documented limits as early as possible. Limits should be enforced at gateways or proxies where practical and repeated within applications for critical constraints. For operations such as bulk requests and file uploads, set limits based on expected workloads rather than relying on broad global thresholds.

API Governance, Testing, and Remediation

23. Continuously Assess API Security Posture

API security posture should be assessed continuously because APIs, configurations, and threats change throughout the software lifecycle. To identify weaknesses as they appear, automated tools can monitor:

  • API inventories
  • Authentication settings
  • Exposed endpoints
  • Data flows
  • Policy violations

Assessments should cover production environments as well as development and staging systems that may be externally accessible. Security teams should establish measurable baselines for controls such as encryption, authorization, schema validation, and logging. Changes that weaken these controls should trigger alerts or remediation workflows.

24. Test APIs for Vulnerabilities and Misconfigurations

API testing should combine automated scanning with targeted manual testing to identify vulnerabilities that tools may miss. Tests should cover:

  • Authentication
  • Authorization
  • Injection
  • Business logic
  • Rate limiting
  • Input validation
  • Security configuration

Security testing should also include common API-specific risks such as broken object-level authorization and unrestricted access to sensitive operations. Testing should be integrated into development and deployment pipelines so weaknesses can be found before APIs reach production. Dynamic testing against running APIs can complement static analysis and code review. Periodic penetration testing is also useful for evaluating complex attack paths and verifying whether existing controls resist realistic attacks.

25. Prioritize Risks Based on Severity and Exposure

Not every API vulnerability presents the same level of risk. Remediation priorities should consider technical severity together with factors such as:

  • Internet exposure
  • Data sensitivity
  • API criticality
  • Exploitability
  • Existing compensating controls

A serious authorization flaw in a public API handling customer records, for example, generally requires faster remediation than the same issue in an isolated test environment. Organizations should use consistent risk criteria and remediation deadlines to prevent critical findings from remaining unresolved.

API inventory and classification data can provide important context for prioritization. Findings should also be reassessed when exposure or business use changes, since these changes can significantly increase the impact of an existing weakness.

26. Keep APIs and Dependencies Patched

APIs depend on components that can contain known vulnerabilities, such as:

  • Frameworks
  • Libraries
  • Runtimes
  • Gateways
  • Containers

Organizations should maintain an inventory of these dependencies and monitor relevant security advisories and vulnerability databases. Critical patches should be evaluated and deployed promptly based on exploitability and API exposure.

Automated dependency scanning can identify vulnerable packages during development and after deployment. Teams should also remove unused dependencies and replace components that are no longer maintained. Patch processes should include testing and rollback procedures so security updates can be deployed quickly without creating unnecessary service disruption.

27. Manage API Versions and Retire Deprecated Endpoints

API versioning allows organizations to introduce changes without unexpectedly breaking existing clients, but old versions can become a security liability. Each supported version should have:

  • A defined owner
  • A maintenance status
  • A retirement date

Deprecated versions should continue receiving necessary security fixes until they are removed from service. Organizations should monitor usage before retiring an endpoint and provide clients with a clear migration path to supported versions.

Once the retirement date is reached, deprecated endpoints should be disabled at gateways, routing layers, and backend services rather than merely removed from documentation. This prevents forgotten API versions from remaining accessible as unmanaged attack surfaces.

Applying API Security Best Practices with Cequence API Security

Implementing 27 controls across discovery, edge protection, access management, payload hygiene, and governance is difficult to sustain manually, especially as API estates change daily. Cequence API Security is an AI-first solution that discovers, monitors, and tests APIs while assessing a broad range of risks that can lead to compliance or governance issues, data loss, and business disruption. It brings API discovery and inventory, risk identification and classification, security testing, sensitive data protection, OWASP API Security Top 10 risk categorization, and attack surface reduction into a single product, giving IT, security, and development teams the visibility and control needed to run a robust API security program.

Key capabilities of Cequence API Security:

  • Comprehensive API discovery and inventory:
    Discovers internal, external, and third-party APIs along with edge, infrastructure, gateway, and hosting providers, combining inside-out and outside-in discovery for both attack surface and internal API visibility. Cequence integrates directly with existing infrastructure such as API gateways, or can be deployed inline.
  • Continuous risk visibility:
    Automatically identifies documented, undocumented, third-party, and shadow API endpoints to build a runtime API catalog, then assesses each one for risks related to access control, sensitive data leakage, and conformance with the published API specification, generating specifications automatically when none exist. Rules and prioritization are user configurable with no coding or scripting.
  • Sensitive data exposure prevention:
    Identifies and masks sensitive data using ML-based rules with predefined patterns, such as credit card numbers, and customizable patterns. Sensitive data patterns are supported worldwide, differentiating a US driver’s license number from a Saudi National ID number, and data is identified wherever it appears without having to define which APIs transact it.
  • Integrated API security testing:
    Enables IT and development teams to test APIs and remediate vulnerabilities and coding errors both pre-production and at runtime. Test plans can be generated automatically from Postman collections or API specifications, with support for CI/CD pipelines, IDEs, and stand-alone testing.
  • Compliance-ready risk rules and reporting:
    Ships more than 250 pre-built risk rules mapped to 25 global frameworks, including every version of the OWASP API Security Top 10, PCI DSS, GDPR, HIPAA, SOC 2, ISO 27001, and NIST CSF. Audit-ready reports generate in a single click from live data, mapping findings to each framework’s controls, scoring risk by control area, and providing remediation guidance for every gap.
  • API attack protection:
    Protects web, mobile, and API applications from attacks that cause data loss, theft, and fraud, using ML-powered threat detection and analytics plus integration with third-party defenses such as WAFs and API gateways. Cequence Bot Management adds native mitigation including blocking, logging, rate limiting, header injection, and deception.
  • AI-first architecture with built-in AI assistant and MCP server:
    A built-in AI Assistant answers questions such as which public APIs handle sensitive data and returns ranked, evidence-backed findings teams can act on in the same conversation. Every capability is exposed as MCP tools for internal agentic workflows, with governance built in. Read actions run freely while every write requires human-in-the-loop approval that shows the exact change first.

See how Cequence API Security can help you put these best practices into practice across your entire API estate – explore Cequence API Security.