API security is the practice of protecting application programming interfaces—which now account for more than 80% of all internet traffic—from cyber threats through authentication, encryption, and monitoring controls. This proactive approach prevents data breaches, unauthorized access, and service disruptions that can cost organizations millions in damages and reputation loss. The strategies below will help you build comprehensive API protection that scales with your cloud environment.
Catch code risks before you deploy
Learn how Wiz Code scans IaC, containers, and pipelines to stop misconfigurations and vulnerabilities before they hit your cloud.

If you want to jump into a specific practice now, you can navigate to the specific section below:
11 API security best practices and recommendations
Let's explore 11 best practices and advanced insights to help you strengthen your API security tools and strategy:
1. Implement Continual API discovery
# Example code for API discovery
import requests
response = requests.get('https://api.yourapp.com/discover')
if response.status_code == 200:
print("API is active and discoverable.")Continuous API discovery is the automated process of identifying and cataloging all APIs across your infrastructure in real-time. This practice prevents shadow APIs—undocumented or forgotten endpoints—from creating security blind spots in your environment. Modern organizations often have hundreds of APIs across different teams, making manual tracking impossible.
One 2024 study showed the percentage of organizations with a full API inventory dropped to just 27%, making automated discovery essential for comprehensive security coverage.
Regular audits allow you to identify and document all active APIs to verify that they adhere to security standards. You can use a feature like Wiz's Dynamic Scanner, for example, to automate the discovery process.
Continuous API discovery also helps you identify shadow APIs, which are unauthorized or forgotten APIs that developers deploy. These APIs pose security risks to your system because your teams likely aren't performing regular security checks on them. For example, developers may create a potential vulnerability when they deploy an API endpoint like /old_endpoint for a beta feature and never remove it.
To fix this, you should implement a system to detect and manage unauthorized or forgotten APIs. From there, you can either bring them into compliance or decommission them.
2. Encrypt traffic in every direction
// Example code to enforce HTTPS
if (window.location.protocol !== "https:") {
window.location.protocol = "https:";
}API traffic encryption protects data as it moves between clients and servers using protocols like HTTPS and TLS. This prevents attackers from intercepting sensitive information during transmission.
Key encryption requirements:
HTTPS with valid SSL certificates for all API communications
TLS 1.2 or higher to protect against man-in-the-middle attacks
End-to-end encryption for API keys and authentication tokens
Modern TLS versions automatically defend against message tampering and forgery attempts, making encryption your first line of defense against network-based attacks.
3. Authenticate and authorize everything
// Example JWT validation
const jwt = require('jsonwebtoken');
const token = JWT_TOKEN";
const secret = SECRET_KEY";
try {
const decoded = jwt.verify(token, secret);
console.log(decoded);
} catch(err) {
console.log("Invalid token.");
}API authentication and authorization verify user identity and control resource access to prevent unauthorized API usage. Authentication confirms who is making the request—for example, through proper OIDC integration – while authorization determines what they can access.
Effective authentication methods:
JSON Web Tokens (JWT) for stateless user verification
OAuth 2.0 for secure third-party access delegation
OpenID Connect (OIDC) for identity layer authentication
These protocols allow users to grant limited access to applications without exposing their primary credentials, reducing the risk of credential theft and misuse.
4. Follow the principle of least privilege
# Example RBAC check
def has_permission(user, action):
roles = user.get_roles()
for role in roles:
if action in role.permissions:
return True
return FalseGrant every user or system interacting with your API only the minimum necessary access rights for their roles. For example, you can use role-based access control to define and enforce these privileges.
Following the principle of least privilege (PoLP) limits the potential damage a malicious actor can inflict if they gain access.
5. Be diligent about API documentation
Outdated API documentation can lead to misuse or unintended vulnerabilities. When you change an API, update your documentation as well to reflect those changes. Additionally, document every endpoint, including those for internal use, to help developers understand proper usage and potential risks.
Tools like Redoc can simplify this process by providing interactive API documentation. Similarly, Swagger can auto-generate documentation to ensure consistency and comprehensiveness.
6. Validate your data
// Example input validation
const { check, validationResult } = require('express-validator');
app.post('/user', [
check('username').isAlphanumeric(),
check('password').isLength({ min: 5 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Continue processing
});Malicious actors frequently launch injection attacks by introducing harmful data via APIs. However, implementing strict validation can prevent such attacks. Libraries like express-validator in Node.js assist with input validation, making it easier to secure your APIs.
You can also verify that the data structure and size follow predefined schemas to prevent buffer overflow attacks and other potential vulnerabilities.
7. Limit Data exposure
Your API should return only the data that is necessary for its function. Excessive data exposure increases the risk of unintended data breaches.
Always encrypt sensitive data, such as passwords, credit card numbers, and personal identification information, both at rest and in transit. Object-relational mapping tools can also help you effectively filter out sensitive data.
8. Introduce rate limiting and throttling
Distributed denial-of-service, or DDoS, attacks overwhelm APIs and cause service disruptions. You can mitigate such threats by limiting rates and using content delivery networks.
Rate limiting can restrict the requests an IP makes within a certain timeframe. These limitations can mitigate instances when attackers attempt to overload your system with traffic. To do this, content delivery networks spread traffic out across different servers to even out the load.
9. Use gateways to centralize security controls
API gateways provide a protective layer by controlling and monitoring API access while supporting rate limiting, caching, and other essential functions.
These gateways make way for a centralized entry point that makes management and security easier for APIs. You can then add control policies for endpoints, create strong encryptions for communications with HTTPS or TLS, and protect against events like injection or cross-scripting attacks.
10. Test your APIs regularly
Regular vulnerability assessments can help you identify weak points that attackers could exploit. These tests ensure that configuration errors won't expose the system to threats in both the API and supporting workloads.
Nuclei, an open-source vulnerability scanner, allows you to test APIs against known vulnerabilities and misconfigurations. This fast, customizable tool uses YAML templates to describe how to detect specific security vulnerabilities.
11. Conduct diligent API key management
# Example of using environment variables for API keys
import os
API_KEY = os.environ.get('API_KEY')API keys function like passwords for APIs, so you must safeguard them diligently. The widespread exposure of secrets – with 61% of organizations having secrets exposed in public repositories—makes credential scanning critical. Rotate your API keys regularly to prevent unauthorized access and use short-lived tokens for added security.
You can also securely store your API keys using environment variables or secret management tools.
If you would like a more extensive overview of best practices for APIs, download Wiz’s cheat sheet for free.
OWASP API Security Top 10: Critical risks you must address
The OWASP API Security Top 10 is a widely recognized list of the most critical security risks facing APIs. Understanding these risks helps you focus your security efforts where they matter most, especially around authorization, as NIST notes that three of the top 10 OWASP risks relate to it. Here's a quick overview of each risk and what it means for your API security:
1. Broken Object Level Authorization (BOLA): APIs that don't properly check if a user should access a specific object can leak or expose sensitive data. Always validate user permissions for every object request.
2. Broken Authentication: Weak or missing authentication lets attackers impersonate users. Use strong authentication methods and never rely on default credentials.
3. Broken Object Property Level Authorization: Failing to restrict access to sensitive object properties can expose confidential information. Make sure users can only access properties they're allowed to see.
4. Unrestricted Resource Consumption: APIs that don't limit resource usage can be abused, leading to denial of service or high cloud bills. Set sensible rate limits and quotas.
5. Broken Function Level Authorization: Not checking if a user is allowed to perform a certain action can let attackers escalate privileges. Always enforce authorization for every function or endpoint.
6. Unrestricted Access to Sensitive Business Flows: APIs that expose sensitive business processes without controls can be abused for fraud or abuse. Protect critical flows with extra checks and monitoring.
7. Server Side Request Forgery (SSRF): APIs that fetch URLs or resources on behalf of users can be tricked into accessing internal systems. Validate and restrict outbound requests.
8. Security Misconfiguration: Default settings, verbose error messages, or unnecessary features can open up vulnerabilities. Harden your API configuration and keep it simple.
9. Improper Inventory Management: Not keeping track of all your APIs, versions, and endpoints can leave old or undocumented APIs exposed. Maintain a complete, up-to-date API inventory.
10. Unsafe Consumption of APIs: Trusting data from third-party APIs without validation can introduce vulnerabilities. Always validate and sanitize data from external sources.
Addressing these risks is a great way to strengthen your API security program. For more details, check out the official OWASP API Security Top 10 documentation.
API architecture components: Foundational terms
Understanding the key components of API architecture will help you implement stronger security measures. Below are the foundational API terms you should know:
Endpoints are specific paths or URLs to which API services provide access. Each endpoint links to a unique resource or function.
Methods specify the actions you can perform on an endpoint. Examples include GET, POST, PUT, and DELETE, which retrieve, submit, update, and delete data.
Data structures define the format and organization of the data the API sends or receives. It often uses JSON or XML formats.
Once you understand the basics of a functional API, you can review the risks associated with third-party connections.
The State of Code Security Report [2025]
API security is only as strong as the secrets it protects. The State of Code Security Report 2025 found that cloud keys make up a large portion of exposed secrets in public and private repositories, leading to lateral movement risks.
Download reportCommon API vulnerabilities and threats
API vulnerabilities are security weaknesses that attackers exploit to gain unauthorized access, steal data, or disrupt services. Understanding these threats helps organizations implement targeted defenses before attacks occur, which is especially important as API data breaches are up 80% year over year.
Below are some common threats that frequently affect APIs:
| Threats | Detection |
|---|---|
| Broken object-level authorization (BOLA) | BOLAs happen when an API doesn’t validate user access to specific resources. If security fails, attackers can compromise object IDs and access unauthorized data. |
| Security misconfigurations | If your team doesn’t configure API security settings correctly, your organization will be vulnerable to threats, such as unauthorized access or data exposure. |
| Excessive data exposure | If your APIs don’t protect authorization and permissions, they could expose more data than you want them to. Unauthorized users can then access this information. |
| Broken authentication | If your security fails to identify the correct user and roles, cyber attackers can bypass your security checks and access resources due to weak authentication mechanisms. |
| Using components with known vulnerabilities | Strategic attackers can target and breach your infrastructure if an API uses dated components or known vulnerabilities. |
Investing in a unified cloud security solution is the key to tackling these challenges.
For example, Wiz Defend—which is part of Wiz’s comprehensive cloud security platform—identifies and mitigates API security threats in real time. By integrating directly into cloud environments, Wiz Defend provides visibility into API vulnerabilities, detects anomalous behavior, and enforces security policies to prevent exploitation, all to secure APIs at scale and safeguard your cloud applications.
Not only is visibility important, but context is, too. For example, instead of showing a list of issues and potential fixes, Wiz Defend helps you see the most important problems. You can then tackle those pressing security concerns more efficiently.
Challenges in API security
API security challenges stem from the dynamic nature of modern development and evolving threat landscapes. Organizations must balance speed with security while managing complex, interconnected systems.
Primary challenges include:
Development speed pressure that pushes security considerations to later phases
Legacy system integration lacking modern security protocols and standards
Evolving attack methods that require constant adaptation of defensive strategies
These challenges require proactive planning and automated security controls rather than reactive responses to emerging threats.
Real-world API security examples
Securing your APIs and strengthening your organization’s security posture requires a multifaceted approach and continual effort.
Let’s look at some examples of successful and unsuccessful API security:
1. When API security goes wrong
What do China, a cybersecurity company, and the United States Department of the Treasury have in common? A bad API.
On Dec. 30, 2024, the Department of the Treasury notified US representatives that Chinese state-backed hackers stole data from government workstations that same month. The department called it a “major cybersecurity incident” and, as of early 2025, is continuing to investigate how deeply the attack surface and exposure went.
What the department does know, though, is that it’s unfortunately connected to a failure from a cybersecurity company. BeyondTrust, the cybersecurity vendor in this case, had a compromised API key that hackers used to access and reset passwords.
In an official letter, the department’s assistant secretary for management, Aditi Hardikar, explained that “a threat actor had gained access to a key used by the vendor to secure a cloud-based service used to remotely provide technical support for the Treasury Departmental Offices (DO) end users.” She also assured readers that the vendor’s service is no longer in use.
What the letter doesn’t touch on is why so many organizations face avoidable threat exposures like this. Many security departments and companies want to adapt non-cloud-native cybersecurity solutions to the cloud—but cloud infrastructure is vastly different from and far more complex than traditional systems. This security gap opens doors to attackers who know how to exploit those vulnerabilities.
However, stakeholders and security teams can avoid similar situations to the one above by implementing continuous security testing and monitoring using the best practices we covered above. Organizations can build targeted security for the evolving technological landscape by leveraging solutions that are designed specifically for the cloud.
Below, you’ll learn how one data company chose cloud-first security to protect patient data.
2. When companies choose a proactive approach to API security
Artisan, an organization that safeguards thousands of patients’ fertility data, needed a way to improve its cloud posture to protect patient and financial data with a zero-tolerance security infrastructure. Improved cloud security is essential to its reputation and trust, so it was vital for Artisan to streamline compliance for SOC and HIPAA.
As a result, Artisan needed a complete solution to securely protect patients, give providers approved access, and safeguard user data across a cloud environment.
The company chose Wiz to strengthen how it protects data and deploys new products.
If you don't have layers of security measures in place, you’re not going to be at the table very long. We need to be ahead of the curve, and working with Wiz has helped us to do that.
Matthew MazzarielloDevelopment Manager, Artisan
Wiz provides Artisan with a holistic view of its cloud environment so the organization can understand its vulnerabilities. Wiz’s automated risk assessment also helps Artisan’s team prioritize security issues by their level of danger: high, medium, or low. This foundational, all-in-one cloud solution makes all the difference—especially with API security.
As a company with a technology-driven mission, Artisan has quickly embraced the cloud so providers can better care for their patients. As a result, stakeholders can confidently access approved information at the right place and time, as Wiz provides the security, tools, and information to empower security teams to keep it secure.
Artisan also makes security a core part of any development and business growth conversations. This improvement in API security and cloud posture has led the company to adopt and prioritize cloud security so it can lead the industry with the best possible experience and tools.
API security: Going beyond the basics
The API landscape changes quickly, so your team needs to adapt and adopt proactive approaches to consistently keep users safe, maintain data integrity, and remain accessible to the right people at the right time.
Adopting zero trust architecture, for example, prepares your organization for future threats. Zero trust architecture consistently ensures that all users have the correct privileges, no matter their device, time, and location. Multi-factor authentication is one such step toward safer access.
With this architecture, developers can provide:
Continuous authentication for each API request
Mutual TLS for service-to-service communication
PoLP application at the endpoint level
You can also secure your APIs with comprehensive logging and real-time monitoring. Both work together to give organizations a holistic defense against threats. For example, you can start by collecting log data from different systems and 24/7 insights from IT systems for proactive protection.
Additionally, your team can implement multi-factor authentication for improved log-in security. To accomplish this, developers can do the following:
Implement OAuth 2.0 or Open ID Connect
Add risk-based adaptive authentication for API access
Solutions like Wiz Defense provide these advantages, as well as incident response planning, all tailored to API-related threats. Plus, Wiz Defense complies with regulations like GDPR and CCPA so you can rest assured that you meet government standards. The platform also meets industry expectations, such as the OWASP API Security Top 10.
OWASP API Security Top 10 Risks
The OWASP API Security Project offers software developers and cloud security practitioners guidance on preventing, identifying, and remediating the most critical security risks facing application programming interfaces (APIs).
Leggi di piùWiz: Your solution for improved API security
Wiz helps protect your APIs across the cloud lifecycle by continuously discovering endpoints across clouds (ingesting from Runtime Sensor, API gateways, and specifications), classifying schemas and data sensitivity, and mapping external exposure and service-to-service flows. It detects weak authentication/authorization, excessive data exposure, and misconfigurations, then prioritizes fixes using toxic combinations that correlate identity permissions, network reachability, and sensitive data. All of this runs in a single CNAPP—so you can enforce policies, assess exposure with Attack Surface Scanner, and track risk from build to runtime in one place.
Discover: Build a complete API endpoint inventory by ingesting from Runtime Sensor, API gateways, or specifications. Classify endpoints with schema analysis and filter by cloud subscription to eliminate blind spots.
Assess: Use Attack Surface Scanner to detect external exposure and other potential risks. Identify authentication and authorization misconfigurations, and scan for sensitive data handled by each API.
Prioritize: Leverage toxic combinations to contextualize risks—combining factors like sensitive data processing, external exposure, identity permissions, and network reachability—to surface the most critical issues first.
Wiz helps you quickly find APIs processing sensitive data, pinpoint externally accessible endpoints, detect auth and authorization gaps, and focus remediation where it matters most. Request a demo to see how Wiz secures your APIs and cloud environment.
An agentless, contextual approach to API security
Learn how with Wiz, customers can now simply answer the question of where do I have exposed APIs in my environment with all the context associated with the execution environment.
Frequently asked questions about API security
Other security best practices you might be interested in: