Summary
APIs are a growing attack surface across cloud, mobile, and microservices environments. API security best practices are critical to reduce API risk, prevent unauthorized access, and improve visibility across the API lifecycle.
Why Are API Security Best Practices Needed?
API security refers to the processes, tools, and best practices designed to protect application programming interfaces (APIs) from malicious attacks and misuse. APIs are the gateways that enable communication between different software components. Because APIs often expose sensitive data and critical functions, securing them is crucial to prevent unauthorized access, data breaches, and service disruptions.
Implementing a robust API security strategy requires a layered approach across the entire development lifecycle.
Key best practices include maintaining a complete API inventory, using strong authentication, and shifting API security left.
These best practices can help address threats like the OWASP API Security Top 10.
Effective API security involves more than just applying traditional web security measures. It requires a comprehensive approach that includes authentication, authorization, encryption, input validation, and monitoring. Given the increasing reliance on APIs in cloud services, mobile apps, and microservices architectures, API security is now a core element of cybersecurity programs.
REST APIs are the most common API architecture and are heavily targeted because they expose many HTTP endpoints and often use JSON payloads and bearer tokens. However, API security also applies to GraphQL, gRPC, SOAP, and event-driven APIs.
For example, GraphQL APIs may increase data exposure and resource exhaustion risks, while gRPC APIs often require stronger internal authentication controls.
This is part of a series of articles about API security
API Security Best Practices at a Glance
The following table summarizes the best practices and quick wins you can implement immediately. We cover each best practice in more detail further in the article.
| Best Practice | Details | Quick Wins | Threats Addressed |
| Use strong authentication | Require secure identity verification using OAuth 2.0, OpenID Connect, mTLS, or signed tokens. | Enforce MFA for administrative APIs and short-lived tokens. | Broken authentication, credential abuse |
| Enforce authorization and least privilege | Restrict users and services to only the permissions they need. | Apply role-based access control to all endpoints. | Broken object/function-level authorization |
| Maintain a complete API inventory | Track all APIs, versions, environments, owners, and exposed data flows across production and non-production systems. | Create a centralized API catalog and require ownership metadata for every API. | Improper inventory management, shadow APIs, outdated APIs |
| Discover shadow and zombie APIs | Identify undocumented, forgotten, deprecated, or unmanaged APIs that may bypass security controls. | Use automated API discovery from gateways, traffic, and repositories. | Shadow APIs, unauthorized access, outdated services |
| Compare API documentation against implementation | Detect gaps between OpenAPI specifications and real runtime behavior. | Regularly validate runtime traffic against API specs. | Excessive data exposure, undocumented endpoints |
| Validate APIs early and continuously | Continuously test schemas, authentication, permissions, and business logic as APIs evolve. | Add automated contract validation and regression testing. | Misconfigurations, schema abuse, insecure changes |
| Store and rotate API keys securely | Protect API keys using secrets managers and rotate them regularly. | Remove hardcoded keys from repositories and logs. | Credential theft, unauthorized API access |
| Encrypt data in transit | Protect API traffic using HTTPS/TLS. | Redirect all HTTP traffic to HTTPS and disable weak ciphers. | Data interception, session hijacking |
| Encrypt sensitive data at rest | Encrypt stored API data, backups, logs, and queues. | Enable database encryption and centralized key management. | Data breaches, unauthorized storage access |
| Validate inputs against strict schemas | Reject malformed or unexpected input before processing. | Use schema validation for all request payloads. | Injection attacks, malformed requests |
| Sanitize API data | Clean and encode data before storage, logging, or display. | Escape user-generated content and remove sensitive fields from responses. | XSS, injection, data leakage |
| Limit excessive data exposure | Return only the minimum data required for each request. | Use response filtering and field allowlists. | Excessive data exposure, privacy leaks |
| Apply rate limiting | Restrict request frequency per user, IP, or token. | Add stricter limits to login and password reset endpoints. | Brute force attacks, scraping, denial of service |
| Use throttling based on usage patterns | Dynamically restrict suspicious or resource-intensive behavior. | Throttle expensive search and export operations. | Resource exhaustion, business flow abuse |
| Use an API gateway as a policy enforcement point | Centralize authentication, logging, rate limiting, and routing controls. | Apply common security policies through the gateway. | Inconsistent security controls, traffic abuse |
| Harden HTTP headers and CORS | Configure secure headers and restrict cross-origin access. | Remove wildcard CORS settings for sensitive APIs. | Browser-based attacks, unauthorized web access |
| Log and monitor API activity continuously | Monitor requests, authentication events, and abnormal behavior in real time. | Centralize API logs and alert on suspicious activity. | Account takeover, scraping, unauthorized access |
| Shift API security left | Integrate security testing during design, development, and CI/CD stages. | Scan OpenAPI files and run security tests in pull requests. | Broken authentication, authorization flaws, insecure design |
| Centralize visibility with an AppSec platform | Consolidate API discovery, testing, monitoring, and remediation workflows. | Correlate API findings with code and runtime risk data. | Security blind spots, fragmented visibility |
Who Needs API Security Best Practices?
Any organization that develops, uses, or manages APIs needs API security. As businesses rely more on APIs to connect applications, services, and users, APIs become a critical part of the attack surface. Security is necessary not only for preventing data breaches, but also for maintaining visibility, compliance, and operational stability across modern software environments.
- Application security teams need API security to identify vulnerabilities, track API changes, and prioritize remediation efforts based on business risk. APIs can quickly grow across environments, making manual inventory management difficult.
- Developers and engineering teams need API security to detect issues early in the software development lifecycle. Early discovery helps prevent vulnerable APIs from reaching production and reduces the cost of fixing security problems later.
- DevOps and platform engineering teams use API security to integrate scanning and monitoring into CI/CD pipelines. This helps maintain visibility into APIs without adding separate tools or workflows.
- Security leaders and CISOs need API security to maintain a complete understanding of the organization’s attack surface. Unknown, undocumented, or outdated APIs can create hidden risks that are difficult to govern without continuous discovery and monitoring.
- Organizations using microservices, cloud-native applications, and mobile apps require API security because these architectures depend heavily on APIs for communication between systems and services.
- Enterprises handling sensitive data such as financial information, healthcare records, or customer data need API security to enforce authentication, authorization, encryption, and compliance requirements.
- Companies with large or rapidly changing development environments benefit from automated API discovery and change tracking, which help maintain an accurate inventory of active, deprecated, and undocumented APIs.
- Teams adopting DevSecOps practices need API security to support shift-left security approaches, allowing vulnerabilities to be identified during development instead of after deployment.
Common API Security Threats: OWASP API Top 10
Let’s review the top 10 API security risks according to the Open Web Application Security Project (OWASP).
API1:2023: Broken Object Level Authorization
Broken Object Level Authorization occurs when an API does not properly verify whether a user has permission to access a specific object, record, or resource. In many APIs, objects are referenced directly through identifiers such as user IDs, order IDs, invoice IDs, account numbers, file IDs, or transaction IDs. If authorization checks are missing or incomplete, an attacker may be able to change these identifiers in an API request and access data that belongs to another user or organization.
This threat is especially common because APIs are often designed to expose backend objects directly to web, mobile, and third-party applications. Even when a user is properly authenticated, the API must still confirm that the user is authorized to access each individual object being requested. Strong object-level authorization, server-side permission checks, and avoiding reliance on client-side controls are essential for preventing unauthorized data access.
Related best practices:
- Object-level authorization checks: Verify ownership or permissions for every requested object on the server side before returning data.
- Least privilege access: Limit users and services to only the records and resources they actually need.
- Indirect object references: Use opaque identifiers instead of predictable sequential IDs to reduce enumeration risk.
- Centralized authorization logic: Apply authorization consistently across all endpoints and services to avoid gaps.
- Access control testing: Regularly test APIs for IDOR and cross-tenant access issues before deployment.
API2:2023: Broken Authentication
Broken Authentication refers to weaknesses in how an API verifies user or system identity. This can include poor password policies, insecure session handling, weak or predictable tokens, missing token expiration, improper JWT validation, credential stuffing exposure, or failure to protect login and password reset flows. When authentication is flawed, attackers may be able to impersonate legitimate users or gain unauthorized access to sensitive systems.
APIs are frequent targets for authentication attacks because they often support automated access and may be used by web apps, mobile apps, integrations, and bots. To reduce this risk, organizations should use strong authentication mechanisms, properly validate tokens, enforce rate limits on login attempts, monitor suspicious behavior, and ensure that credentials and session tokens are never exposed in logs, URLs, or insecure storage.
Related best practices:
- Multi-factor authentication (MFA): Adds an additional identity check that reduces the impact of stolen credentials.
- Strong token validation: Verify signatures, expiration, issuer, and audience values for JWTs and access tokens.
- Secure credential storage: Store passwords using modern hashing algorithms such as bcrypt or Argon2.
- Rate limiting on authentication endpoints: Slows brute-force attacks and credential stuffing attempts.
- Short-lived tokens: Reduce the time window attackers can use stolen session or access tokens.
API3:2023: Broken Object Property Level Authorization
Broken Object Property Level Authorization occurs when an API exposes or allows modification of object properties that a user should not be able to view or change. For example, an API response may return sensitive fields such as internal notes, account status, salary information, or personally identifiable information. Similarly, an API request may allow a user to modify restricted fields such as role, isAdmin, accountBalance, or approvalStatus.
This threat often appears when APIs automatically serialize full backend objects or accept full request payloads without filtering fields based on the user’s permissions. Developers should carefully define which object properties each user role can read or modify. Proper input validation, response filtering, allowlists, and server-side enforcement of field-level permissions help prevent both excessive data exposure and unauthorized property changes.
Related best practices:
- Field-level access control: Define which object properties each role can read or modify.
- Response filtering: Return only the fields required by the client instead of entire backend objects.
- Input allowlists: Explicitly allow only approved fields in update requests to prevent mass assignment.
- Schema validation: Validate request payloads against strict schemas before processing.
- Sensitive data classification: Identify confidential fields so they receive stronger protection and review.
API4:2023: Unrestricted Resource Consumption
Unrestricted Resource Consumption happens when an API allows clients to consume excessive system resources without proper limits. Attackers can abuse endpoints that require heavy processing, large database queries, file uploads, image conversions, report generation, or expensive third-party service calls. This can lead to degraded performance, service outages, increased infrastructure costs, or denial-of-service conditions.
APIs should be designed with clear limits on request size, response size, query complexity, upload volume, execution time, and request frequency. Rate limiting, quotas, pagination, timeouts, caching, and cost-based throttling can help control resource usage. It is also important to monitor unusual traffic patterns and identify endpoints that are expensive to run, especially when they can be triggered repeatedly or anonymously.
Related best practices:
- Rate limiting: Restrict how frequently clients can call expensive or sensitive endpoints.
- Pagination and query limits: Prevent excessively large database queries and oversized responses.
- Request timeouts: Stop long-running requests from consuming resources indefinitely.
- Payload size restrictions: Limit upload and request sizes to reduce abuse and infrastructure strain.
- Monitoring and alerting: Detect unusual spikes in traffic or resource usage before they cause outages.
API5:2023: Broken Function Level Authorization
Broken Function Level Authorization occurs when an API fails to restrict access to sensitive functions or actions based on the user’s role or permissions. For example, a regular user might be able to call an admin endpoint, delete another user’s content, export private data, change account settings, or approve transactions. This often happens when backend authorization rules are inconsistent or when developers assume hidden endpoints cannot be discovered.
Attackers commonly test APIs by changing HTTP methods, modifying paths, guessing administrative routes, or calling endpoints that are not exposed in the user interface. Every API function should enforce authorization on the server side, regardless of whether the function appears in the frontend. Role-based access control, permission checks, deny-by-default policies, and regular testing of privileged endpoints are key defenses.
Related best practices:
- Role-based access control (RBAC): Restrict functions and actions based on defined user roles.
- Deny-by-default policies: Block access unless a permission is explicitly granted.
- Server-side authorization enforcement: Never rely on frontend controls or hidden UI elements for protection.
- Privilege testing: Regularly test APIs using low-privilege accounts to identify exposed functions.
- Endpoint inventory reviews: Ensure administrative and internal endpoints are properly protected.
API6:2023: Unrestricted Access to Sensitive Business Flows
Unrestricted Access to Sensitive Business Flows occurs when an API exposes important business processes without sufficient protection against abuse. These flows may be technically valid but harmful when automated or performed at scale. Examples include bulk account creation, ticket scalping, fake reviews, coupon abuse, inventory hoarding, password reset abuse, referral fraud, and excessive checkout attempts.
This threat is different from traditional technical vulnerabilities because the attacker may be using the API exactly as designed. The problem is that the business flow lacks controls to detect or prevent abuse. Organizations should identify high-value workflows, define expected usage patterns, apply rate limits and behavioral detection, use anti-automation controls where appropriate, and monitor for activity that indicates fraud, scraping, or manipulation.
Related best practices:
- Behavioral monitoring: Detect abnormal usage patterns that indicate automation or fraud.
- Rate limiting for high-risk flows: Reduce abuse of registration, checkout, or password reset processes.
- Bot detection controls: Use CAPTCHA, device fingerprinting, or challenge systems where appropriate.
- Transaction limits: Restrict how frequently sensitive actions can be performed within a time window.
- Fraud analytics: Monitor business workflows for indicators of scraping, hoarding, or manipulation.
API7:2023: Server Side Request Forgery
Server Side Request Forgery occurs when an API accepts a user-supplied URL or network destination and causes the server to make a request to that destination. Attackers may exploit this behavior to access internal systems, scan private networks, reach cloud metadata services, or bypass firewall protections. SSRF is especially dangerous when the vulnerable server has access to systems that are not exposed publicly.
APIs that fetch remote resources, process webhooks, import files from URLs, generate previews, or connect to third-party services may be vulnerable if they do not validate destinations carefully. Defenses include using allowlists, blocking private IP ranges, disabling redirects where appropriate, validating URLs after DNS resolution, and isolating services that make outbound requests. Sensitive internal services should never rely only on network location as a security boundary.
Related best practices:
- Outbound request allowlists: Allow connections only to approved external destinations.
- Private network blocking: Prevent requests to internal IP ranges and cloud metadata services.
- URL validation after DNS resolution: Reduce bypass techniques that exploit DNS rebinding.
- Network segmentation: Isolate systems that make outbound requests from sensitive internal services.
- Restricted redirect handling: Limit or disable automatic redirects to untrusted destinations.
API8:2023: Security Misconfiguration
Security Misconfiguration includes insecure settings, missing hardening, unnecessary features, or poorly configured infrastructure that exposes an API to attack. Examples include overly permissive CORS policies, verbose error messages, exposed debug endpoints, default credentials, unnecessary HTTP methods, missing security headers, outdated software, and misconfigured cloud storage or gateways. These issues can give attackers valuable information or direct access to sensitive functionality.
Misconfigurations often happen because APIs depend on many layers, including application code, web servers, API gateways, cloud services, containers, identity providers, and monitoring tools. Security baselines, automated configuration checks, patch management, environment separation, and secure deployment pipelines help reduce this risk. Production systems should be hardened, regularly reviewed, and configured to reveal as little internal information as possible.
Related best practices:
- Secure configuration baselines: Standardize hardened settings across environments and services.
- Patch and dependency management: Keep software and frameworks updated to reduce known vulnerabilities.
- Environment separation: Prevent test and development systems from exposing production data or features.
- Minimal attack surface: Disable unused services, HTTP methods, and debug functionality.
- Automated configuration scanning: Continuously detect insecure settings and policy violations.
API9:2023: Improper Inventory Management
Improper Inventory Management occurs when an organization does not maintain an accurate and up-to-date inventory of its APIs, versions, environments, and endpoints. As systems evolve, old versions, test endpoints, staging APIs, deprecated services, or undocumented “shadow APIs” may remain accessible. These forgotten assets may lack proper authentication, logging, patching, or security testing.
Attackers often look for overlooked APIs because they may be easier to exploit than current, well-maintained endpoints. Organizations should maintain a complete API inventory that includes ownership, purpose, data sensitivity, environment, version, and exposure level. API documentation, discovery tools, lifecycle management, deprecation processes, and continuous monitoring help ensure that every exposed API is known, governed, and protected.
Related best practices:
- Centralized API inventory: Maintain a complete list of APIs, versions, owners, and environments.
- API discovery scanning: Continuously identify undocumented or shadow APIs exposed to networks.
- Version lifecycle management: Retire deprecated API versions in a controlled and timely manner.
- Ownership and governance: Assign clear responsibility for maintaining and securing each API.
- Continuous exposure monitoring: Regularly review externally accessible endpoints for unexpected changes.
API10:2023: Unsafe Consumption of APIs
Unsafe Consumption of APIs occurs when an application blindly trusts data, files, redirects, or responses received from third-party APIs. If an external API is compromised, manipulated, spoofed, or returns unexpected content, the consuming application may become vulnerable. Risks include injection attacks, malicious redirects, data leaks, insecure deserialization, account takeover, or supply-chain-style compromise.
Organizations should treat third-party API responses as untrusted input, even when the provider is reputable. Responses should be validated, sanitized, and checked against expected schemas before being processed or displayed. Additional protections include using secure communication, verifying certificates, limiting permissions granted to integrations, monitoring provider behavior, handling failures safely, and avoiding the exposure of sensitive internal data to external services unless necessary.
Related best practices:
- Schema validation for external data: Verify third-party responses match expected formats before processing.
- Input sanitization: Treat all external API data as untrusted to reduce injection and parsing risks.
- Secure transport verification: Use TLS and validate certificates when communicating with external services.
- Least privilege integrations: Grant third-party APIs only the permissions they absolutely require.
- Resilient error handling: Safely handle failures or malformed responses without exposing internal systems.
Key API Security Best Practices
1. Use Strong Authentication
Strong authentication ensures that only legitimate users, applications, and services can access an API. APIs should use secure authentication mechanisms such as OAuth 2.0, OpenID Connect, mutual TLS, short-lived tokens, or signed requests where appropriate. Weak passwords, long-lived tokens, shared credentials, and poorly validated JWTs increase the risk of unauthorized access. Authentication should be enforced consistently across all endpoints, including internal and administrative APIs.
Action items:
- Require modern authentication protocols such as OAuth 2.0 or OpenID Connect.
- Enforce multi-factor authentication for administrative and high-risk access.
- Use short-lived access tokens and rotate refresh tokens regularly.
- Validate JWT signatures, expiration times, issuers, and audiences.
- Block weak passwords and monitor for credential stuffing activity.
- Prevent credentials and tokens from appearing in logs or URLs.
Pro tips:
- Separate machine-to-machine authentication from user authentication to reduce token misuse risks.
- Bind tokens to specific devices, clients, or certificates when possible to reduce replay attacks.
- Monitor token usage patterns and revoke tokens automatically when behavior changes unexpectedly.
2. Enforce Authorization and Least Privilege
Authentication confirms identity, but authorization determines what that identity is allowed to do. Every API request should be checked against server-side authorization rules to ensure the user, application, or service has permission to access the requested function, object, or data field. Least privilege means granting only the minimum access required for a specific role or task. APIs should enforce role-based, attribute-based, or policy-based access controls depending on the business need.
Action items:
- Enforce authorization checks on every API request.
- Apply role-based or attribute-based access controls consistently.
- Restrict users and services to only the permissions they require.
- Validate object-, function-, and field-level permissions server side.
- Remove unused permissions and stale service accounts regularly.
- Test APIs using low-privilege accounts during security reviews.
Pro tips:
- Store authorization policies centrally so changes propagate consistently across services.
- Use short-lived privilege elevation instead of granting permanent administrative access.
- Log authorization decisions to help detect privilege abuse and policy gaps.
3. Maintain a Complete API Inventory
A complete API inventory gives security and engineering teams visibility into every API endpoint, version, environment, owner, and data flow across the organization. Without an accurate inventory, teams may overlook exposed APIs, undocumented endpoints, deprecated services, or APIs handling sensitive data. This makes it difficult to assess risk, apply consistent controls, or respond quickly when vulnerabilities are discovered.
Action items:
- Track all APIs, versions, environments, and owners centrally.
- Document exposed endpoints, authentication methods, and data sensitivity.
- Update the inventory automatically through CI/CD and discovery tools.
- Include internal, partner, third-party, and staging APIs.
- Retire deprecated APIs through a formal lifecycle process.
- Review the inventory regularly for accuracy and completeness.
Pro tips:
- Tag APIs with business criticality and data classification to prioritize security efforts faster.
- Correlate inventory data with traffic logs to identify undocumented but active APIs.
- Include infrastructure dependencies such as gateways and queues to understand exposure paths.
4. Discover Shadow and Zombie APIs
Shadow APIs are undocumented or unknown APIs that exist outside formal security and governance processes. Zombie APIs are outdated, deprecated, or forgotten APIs that remain accessible even though they are no longer actively maintained. Both can create serious security risks because they may lack modern authentication, patching, monitoring, and authorization controls.
Action items:
- Scan networks and gateways regularly for undocumented APIs.
- Identify deprecated endpoints that are still accessible externally.
- Remove unused APIs and disable abandoned environments.
- Compare observed traffic against official API documentation.
- Monitor DNS records, cloud assets, and repositories for forgotten services.
- Apply the same security controls to non-production APIs.
Pro tips:
- Analyze API traffic metadata to find endpoints that bypass official gateways.
- Use passive discovery from logs and service meshes to detect hidden APIs with low operational impact.
- Track API usage trends over time to identify dormant endpoints before attackers do.
5. Compare API Documentation Against Implementation
API documentation often differs from how APIs actually behave in production. Endpoints may accept undocumented parameters, expose additional response fields, support unexpected methods, or return sensitive data not listed in the specification. These gaps can create security risks because teams may believe an API is safer or simpler than it really is. Comparing API documentation against real implementation helps identify drift between intended and actual behavior.
Action items:
- Validate production APIs against OpenAPI or schema definitions.
- Detect undocumented endpoints, methods, parameters, and response fields.
- Review APIs for unexpected error messages and debug behavior.
- Reject requests that do not match approved schemas.
- Update documentation whenever APIs change.
- Include documentation validation in CI/CD pipelines.
Pro tips:
- Use contract testing to detect implementation drift before deployment.
- Capture real production traffic samples to compare actual behavior against specifications.
- Monitor for undocumented response fields because they often reveal sensitive internal data.
6. Validate APIs Early and Continuously
API validation should begin during design and continue throughout development, testing, deployment, and runtime. Early validation helps catch insecure patterns such as missing authentication, weak schema definitions, excessive permissions, or unclear data boundaries before they become production vulnerabilities. Continuous validation is equally important because APIs change frequently. New endpoints, updated parameters, modified responses, and changing business logic can introduce new risks.
Action items:
- Review API designs for security risks before development starts.
- Validate schemas, authentication rules, and access controls in CI/CD pipelines.
- Perform automated API security testing during development and deployment.
- Continuously monitor APIs for configuration drift and unexpected changes.
- Re-test APIs after major feature releases or architecture changes.
- Include security validation in pull request and code review workflows.
Pro tips:
- Treat API specifications as security contracts, not just documentation artifacts.
- Prioritize runtime validation for high-risk business workflows, not only technical vulnerabilities.
- Combine static analysis with runtime traffic inspection to detect logic flaws more effectively.
7. Store and Rotate API Keys Securely
API keys should be treated as sensitive credentials because they can grant access to applications, services, or data. They should never be hardcoded in source code, stored in public repositories, exposed in client-side applications, or logged in plaintext. Secure storage solutions such as secrets managers, encrypted environment variables, and vault systems should be used instead.
Action items:
- Store API keys in secrets managers or encrypted vault systems.
- Rotate keys regularly and revoke unused credentials immediately.
- Prevent API keys from being hardcoded in applications or repositories.
- Restrict key permissions to the minimum required scope.
- Monitor repositories and logs for accidental key exposure.
- Separate development, staging, and production credentials.
Pro tips:
- Issue unique API keys per application, environment, and customer to improve traceability.
- Use automated rotation pipelines so key changes do not depend on manual coordination.
- Detect unusual geographic or behavioral usage patterns to identify stolen keys quickly.
8. Encrypt Data in Transit
APIs should encrypt data in transit to protect requests and responses from interception, tampering, and eavesdropping. Transport Layer Security, commonly implemented through HTTPS, should be required for all API communication, including internal service-to-service traffic and external client connections. Encryption in transit is especially important when APIs handle credentials, tokens, personal data, payment details, healthcare information, or business-sensitive records.
Action items:
- Require HTTPS for all API communication.
- Disable insecure SSL and TLS versions and weak cipher suites.
- Encrypt internal service-to-service traffic as well as external traffic.
- Redirect or block unencrypted HTTP requests.
- Validate certificates and certificate chains properly.
- Protect sensitive tokens and credentials during transmission.
Pro tips:
- Use mutual TLS for high-trust internal services and partner integrations.
- Monitor certificate expiration continuously to avoid unexpected outages.
- Encrypt east-west traffic inside cloud and container environments, not just internet-facing traffic.
9. Encrypt Sensitive Data at Rest
Sensitive API data should also be encrypted when stored in databases, object storage, logs, backups, queues, and caches. Encryption at rest helps reduce the impact of unauthorized access to storage systems or infrastructure. This is particularly important for personal information, financial records, authentication tokens, intellectual property, and regulated data. Encryption should be combined with strong key management practices.
Action items:
- Encrypt databases, object storage, backups, and logs containing sensitive data.
- Use centralized key management systems with strict access controls.
- Rotate encryption keys regularly.
- Separate encryption keys from encrypted data storage locations.
- Limit access to decrypted data based on operational need.
- Verify encryption coverage across caches, queues, and temporary storage.
Pro tips:
- Use envelope encryption to simplify large-scale key rotation and reduce key exposure.
- Encrypt sensitive fields individually when full-database encryption is insufficient.
- Monitor decryption activity because abnormal patterns may indicate insider abuse or compromise.
10. Validate Inputs Against Strict Schemas
Strict input validation helps prevent malicious or malformed data from reaching backend systems. APIs should define exactly which parameters, data types, formats, lengths, ranges, and structures are allowed. Requests that do not match the expected schema should be rejected before being processed. Schema validation reduces the risk of injection attacks, business logic abuse, unexpected errors, and resource exhaustion.
Action items:
- Define strict schemas for all requests and parameters.
- Reject unexpected fields, formats, and data types.
- Enforce limits for payload size, nesting depth, and array length.
- Validate file uploads and encoded content carefully.
- Apply server-side validation even when clients validate input.
- Use centralized validation libraries across services.
Pro tips:
- Treat optional fields carefully because attackers often abuse loosely validated parameters.
- Validate data after deserialization to catch parser-specific inconsistencies.
- Include business-rule validation in addition to technical schema validation.
11. Sanitize API Data
Sanitization helps ensure that data received, stored, returned, or displayed by an API cannot trigger harmful behavior in downstream systems. Even after validation, API data may need to be cleaned, escaped, normalized, or encoded before being inserted into databases, rendered in user interfaces, sent to logs, or passed to third-party services. Sanitization is especially important for user-generated content, file metadata, URLs, HTML, scripts, and text fields that may later appear in another context.
Action items:
- Escape or encode output before rendering data in downstream systems.
- Normalize and clean user-generated content before storage.
- Sanitize file names, URLs, and metadata fields.
- Remove dangerous characters and scripts where appropriate.
- Prevent log injection by sanitizing logged input values.
- Apply context-specific sanitization for HTML, SQL, JSON, and shell usage.
Pro tips:
- Sanitize data at both ingestion and output stages because context changes over time.
- Preserve original raw data securely for forensics while serving sanitized versions operationally.
- Test sanitization logic against polyglot payloads that target multiple parsers simultaneously.
12. Limit Excessive Data Exposure
APIs should return only the data required for a specific request, user role, and business purpose. Excessive data exposure occurs when APIs return full objects, internal fields, sensitive properties, or more records than needed. Even if the frontend hides this information, attackers can inspect raw API responses.
Action items:
- Return only the fields required for each request.
- Filter responses based on user role and permissions.
- Avoid exposing internal identifiers or system metadata unnecessarily.
- Implement pagination and record limits on collection endpoints.
- Review API responses regularly for sensitive fields.
- Use response allowlists instead of hiding fields client side.
Pro tips:
- Build response objects specifically for external APIs instead of serializing backend models directly.
- Monitor production traffic for rarely used response fields that may expose unnecessary data.
- Test APIs with intercepting proxies to verify hidden frontend data is not still exposed.
13. Apply Rate Limiting
Rate limiting restricts how many requests a client, user, token, or IP address can make within a defined time period. It helps protect APIs from brute-force attacks, credential stuffing, scraping, spam, denial-of-service attempts, and accidental overuse. Without rate limits, attackers can automate large volumes of requests at low cost. Rate limits should be applied based on endpoint sensitivity, authentication status, user role, and business function.
Action items:
- Apply request limits based on IP address, token, user, or client.
- Use stricter limits for authentication and sensitive endpoints.
- Return consistent error responses when limits are exceeded.
- Monitor for distributed attacks that bypass simple IP-based controls.
- Adjust limits based on endpoint cost and abuse risk.
- Document rate limits clearly for API consumers.
Pro tips:
- Combine rate limits with behavioral analytics to detect low-and-slow attacks.
- Use separate quotas for read-heavy and write-heavy operations to preserve availability.
- Apply burst controls in addition to rolling limits to reduce sudden traffic spikes.
14. Use Throttling Based on Usage Patterns
Throttling adjusts API access based on behavior, resource consumption, or abnormal usage patterns. Unlike fixed rate limits, throttling can respond dynamically when a client sends unusual traffic, triggers expensive operations, or behaves differently from expected business patterns. This helps protect performance and detect abuse. Usage-based throttling can consider request frequency, payload size, query complexity, geographic anomalies, failed authentication attempts, account age, or endpoint cost.
Action items:
- Detect unusual request patterns and slow abusive clients dynamically.
- Throttle expensive operations more aggressively than lightweight requests.
- Adjust throttling based on authentication status and reputation signals.
- Monitor failed logins, scraping behavior, and geographic anomalies.
- Protect high-risk workflows such as checkout and password reset flows.
- Use adaptive throttling during traffic spikes or attacks.
Pro tips:
- Incorporate business context such as account age or transaction history into throttling decisions.
- Apply cost-based throttling using query complexity and backend resource consumption metrics.
- Use progressive throttling that increases restrictions gradually instead of blocking immediately.
15. Use an API Gateway as a Policy Enforcement Point
An API gateway can serve as a centralized control point for authentication, authorization, routing, rate limiting, logging, traffic filtering, and policy enforcement. By placing common controls at the gateway layer, organizations can apply consistent protections across many APIs and reduce duplicated security logic in individual services. However, an API gateway should not replace secure application logic.
Action items:
- Centralize authentication, logging, and rate limiting at the gateway layer.
- Apply consistent security policies across APIs and environments.
- Block malicious traffic and invalid requests before they reach backend services.
- Use the gateway to enforce TLS and request validation.
- Monitor gateway logs for abuse and policy violations.
- Keep gateway configurations version controlled and reviewed.
Pro tips:
- Use gateways to standardize security headers and token validation across teams.
- Avoid placing complex business authorization logic exclusively in the gateway layer.
- Segment internal and external APIs behind separate gateway policies to reduce exposure.
16. Harden HTTP Headers and CORS
Secure HTTP headers help reduce browser-based and client-side risks when APIs interact with web applications. Headers can control caching, content types, transport security, framing, and other behaviors that affect how clients handle API responses. Misconfigured or missing headers can expose APIs to data leakage, clickjacking, MIME sniffing, or insecure transport risks. CORS should be configured carefully to allow only trusted origins, methods, and headers. Overly permissive settings, such as allowing all origins with sensitive credentials, can expose APIs to unauthorized browser-based access.
Action items:
- Enable strict transport security headers for HTTPS enforcement.
- Configure CORS to allow only trusted origins and methods.
- Disable unnecessary cross-origin credential sharing.
- Prevent MIME sniffing with explicit content type headers.
- Restrict framing where clickjacking risks exist.
- Review headers regularly after infrastructure or framework changes.
Pro tips:
- Validate CORS behavior in browsers because misconfigurations often differ from server expectations.
- Avoid wildcard origins on APIs that use cookies or authorization headers.
- Use separate CORS policies for public APIs and internal administrative interfaces.
17. Log and Monitor API Activity Continuously
Continuous logging and monitoring help teams detect suspicious API behavior, investigate incidents, and understand how APIs are being used. API logs should capture useful security context such as user identity, endpoint, method, status code, source, authentication events, authorization failures, request volume, and unusual access patterns.
Action items:
- Log authentication attempts, authorization failures, and sensitive actions.
- Capture request metadata such as source, method, endpoint, and response status.
- Monitor APIs for unusual traffic spikes and abuse patterns.
- Centralize logs for correlation and investigation.
- Protect logs from tampering and unauthorized access.
- Define alert thresholds for suspicious API activity.
Pro tips:
- Correlate API activity with identity, device, and network telemetry for better detection accuracy.
- Log denied authorization attempts because they often reveal reconnaissance activity.
- Use sampling carefully so high-volume logging does not hide low-frequency attacks.
18. Shift API Security Left
Shifting API security left means identifying and fixing API risks earlier in the software development lifecycle. Instead of waiting until APIs are deployed in production, teams should test designs, specifications, schemas, and code during planning, development, and CI/CD stages. This reduces the likelihood that insecure APIs reach live environments.
Action items:
- Review API designs and schemas before development begins.
- Include API security testing in CI/CD pipelines.
- Train developers on common API security risks and secure design patterns.
- Validate authentication and authorization logic during code review.
- Scan dependencies and frameworks for vulnerabilities continuously.
- Fail builds automatically when critical API security issues are detected.
Pro tips:
- Use reusable secure API templates to reduce inconsistent implementations across teams.
- Involve security engineers during API design reviews instead of only during release stages.
- Prioritize developer-friendly tooling so security checks are adopted instead of bypassed.
19. Automate API Security Testing Across the Lifecycle
Manual API reviews cannot keep pace with fast-moving development teams, frequent releases, and constantly changing API surfaces. Automated API security testing helps identify vulnerabilities, undocumented endpoints, weak configurations, and implementation drift earlier in the software development lifecycle. Testing should begin at the design stage, continue through coding and CI/CD, and extend into runtime monitoring. It is recommended combining API documentation review, source code scanning, dynamic testing, and inventory correlation so teams can catch issues before production while still validating live APIs continuously.
Action items:
- Scan API specifications such as OpenAPI, Swagger, and RAML during the design phase.
- Integrate API security scans into developer tools, pull requests, and CI/CD pipelines.
- Test source code and API implementations for vulnerabilities before merge or release.
- Correlate scan findings with API documentation to detect undocumented or outdated endpoints.
- Use both static and dynamic testing to identify risks across code and running APIs.
Automatically create tickets or remediation tasks for confirmed API security findings.
Pro tips:
- Run API scans at multiple lifecycle stages instead of relying only on pre-production testing.
- Make scan results developer-friendly with clear prioritization and guided remediation.
- Cross-reference automated findings with the API inventory so shadow and zombie APIs do not escape review.
20. Centralize Visibility with an AppSec Platform
A centralized AppSec platform helps security teams manage API risk across discovery, inventory, testing, prioritization, and remediation. Instead of relying on disconnected tools and manual processes, teams can gain a unified view of API assets, vulnerabilities, ownership, exposure, and business context. Centralized visibility is especially valuable for organizations with many applications, microservices, cloud environments, and development teams.
Action items:
- Aggregate API inventory, testing, and monitoring data centrally.
- Correlate vulnerabilities with business criticality and exposure.
- Track remediation status and ownership across teams.
- Integrate runtime telemetry with development and CI/CD systems.
- Monitor API posture continuously across cloud and on-premises environments.
- Use centralized dashboards for reporting and risk prioritization.
Pro tips:
- Prioritize vulnerabilities using exploitability and business impact instead of severity alone.
- Link API assets to owners automatically through source control and deployment metadata.
- Combine runtime traffic analysis with static findings to reduce false positives.
How to Choose API Security Tools
Implementing best practices can be difficult without robust tooling. Organizations need visibility into APIs throughout the software development lifecycle, including undocumented and deprecated endpoints that traditional perimeter tools often miss.
A modern approach should help teams identify API risks earlier, correlate findings across testing methods, and simplify remediation and governance at scale:
- Look for unified platform capabilities: Use a single platform that provides visibility across API and non-API application components instead of managing multiple disconnected security tools.
- Prioritize centralized risk visibility: Maintain a continuously updated inventory of APIs, including shadow and deprecated endpoints, with correlated findings from static and dynamic testing.
- Evaluate remediation support for developers: Provide developers with actionable findings tied directly to source code and API endpoints so issues can be fixed earlier in the SDLC.
- Ensure strong integration with existing workflows: Integrate API discovery and testing into CI/CD pipelines, developer workflows, and existing application security processes.
- Support governance and compliance requirements: Track API changes, authentication updates, and sensitive data exposure to improve auditability and support governance initiatives.
- Assess scalability for enterprise environments: Support large and rapidly changing API ecosystems without requiring manual API registration or maintenance.
- Check for end-to-end (code-to-cloud) coverage: Correlate source-code analysis, documentation analysis, and runtime testing to provide complete visibility across the application lifecycle.
- Leverage automation and ai capabilities: Automate API discovery, inventory management, and risk prioritization to reduce manual effort and improve response times.
- Reduce tool sprawl and operational overhead: Consolidate API security into a broader application security platform to simplify management, reporting, and vendor relationships.
Checkmarx API Security with Checkmarx One
Checkmarx API Security is an integrated capability within Checkmarx One that gives enterprise AppSec and development teams complete, continuous visibility into their entire API footprint. As applications increasingly depend on hundreds or thousands of APIs, traditional WAFs and runtime tools leave teams blind to shadow APIs, zombie APIs, and code-level vulnerabilities introduced before deployment.
Checkmarx API Security discovers APIs at the source by scanning application source code and documentation, surfacing the full inventory, flagging unknown and undocumented endpoints, and correlating findings with SAST and DAST results to enable risk-based remediation. As part of Checkmarx One, it eliminates the need for standalone API tools and gives teams a single view of application security risk across API and non-API components.
Key API security capabilities in Checkmarx One platform:
- Automatic API discovery across the SDLC: Identify API endpoints in source code, documentation, and dynamic testing without requiring manual registration or definition by developers or AppSec teams. APIs are discovered as developers check in or compile source code, providing the earliest possible signal.
- Shadow and zombie API exposure: Surface undocumented APIs and deprecated endpoints that remain accessible, reducing the hidden attack surface that traditional tools cannot see. Checkmarx compares the full discovered inventory against API documentation to identify what is not accounted for.
- Risk-based remediation prioritization: Help AppSec teams and developers triage findings based on business risk and real-world impact rather than raw vulnerability count. The Global API Inventory ranks vulnerabilities by severity across Critical, High, Medium, and Low, enabling teams to focus resources where they matter.
- Correlated SAST and DAST results for end-to-end coverage: Link static findings from source code analysis to dynamic test results, providing a correlated view of API risk across the SDLC. Teams see both code-level and runtime vulnerabilities for the same endpoint in a single inventory.
- API change tracking over time: Monitor changes to API structure, authentication requirements, and sensitive data exposure over time through the API Change Log. Teams can understand how risk was introduced and identify which changes require remediation.
- Consolidated AppSec tooling: Replace standalone API security tools with a capability built into Checkmarx One, reducing tool sprawl, administrative overhead, and the cost of managing multiple vendor relationships. A single platform covers API and non-API components of the same application.