We'll start with the bad news, which you probably already know: APIs are one of the most attractive targets in your stack. As OWASP puts it, "By nature, APIs expose application logic and sensitive data such as Personally Identifiable Information (PII) and because of this, APIs have increasingly become a target for attackers." [1]
AI is adding to that risk. AI coding assistants write more code, and more of that code calls, exposes, or depends on APIs, often with questionable security measures. The flood of new code and PRs means code review and API testing are often less thorough than they should be.
So, can we skip to the good news?
The good news is that shipping clean, trustworthy code and improving API security doesn't have to slow you down. You can scale security and speed at the same time, and it doesn't require spending all your time on testing and code review.
In this article, we'll show you how.
What is API security?
API security is the practice of protecting APIs (Application Programming Interfaces) from attacks, unauthorized access, data breaches, and other threats or vulnerabilities.
APIs let software programs communicate, share data, run code, and pass sensitive information between systems. That makes securing them critical for any company that relies on them to run its application's backend logic. Today, that's almost everybody.
A weak API exposes your entire application to attackers, data breaches, injections, and other preventable security risks.
The 10 most common API security risks
In general, API security risks fall into three main types:
- Authentication and authorization failures: the API doesn't properly or completely verify who is making a request, or what they're allowed to access, before it proceeds with the workflow. This exposes user or system data.
- Vulnerability exploits: the API doesn't have proper or complete configuration, limits, or validation in place to prevent exploitation.
- DoS and DDoS attacks: the API doesn't have the rate, resource, or spending limits in place to stop an attacker from flooding endpoints and exhausting resources.
The OWASP Top 10 API Security Risks list is the reference for the most common and exploitable API vulnerabilities. Here's a quick recap of the 2023 edition [2]:
| Risk | Risk type | What it is | Secure it by |
|---|---|---|---|
| API1: Broken Object Level Authorization (BOLA) | Authorization | APIs that expose endpoints that handle object identifiers risk exposing those objects to unauthorized users. Attackers can manipulate object IDs sent in API requests to reach data that isn't theirs. | Making sure every API endpoint that receives and acts on an object ID also performs an object-level authorization check. |
| API2: Broken Authentication | Authentication | Incorrectly implemented or weak authentication flows let attackers log in or act as other users, or gain unauthorized access. | Securing every authentication endpoint and flow according to best practices, and knowing every path a request can take to authenticate. |
| API3: Broken Object Property Level Authorization | Authorization | Missing or weak authorization checks at the object property level can expose (or let users change) properties they shouldn't have access to. | Checking that the user has access to every object property an endpoint returns or accepts. |
| API4: Unrestricted Resource Consumption | DoS/DDoS | APIs that don't limit calls or resource use can be abused to burn through network bandwidth, CPU, memory, or paid third-party requests. | Rate limiting and throttling API calls, and setting limits on resources each request can use. |
| API5: Broken Function Level Authorization | Authorization | Unclear or improperly implemented access control, hierarchies, or roles can let regular users reach administrative functions. | Denying access by default and granting it explicitly by role, then checking that every endpoint enforces the right level of access. |
| API6: Unrestricted Access to Sensitive Business Flows | Vulnerability | An API that controls a business flow (such as making a purchase) isn't protected against aggressive automation, so attackers can abuse it at scale. | Identifying business flows that would cause harm if used excessively, then adding protections that slow down or block automated abuse. |
| API7: Server Side Request Forgery (SSRF) | Vulnerability | The API fetches a remote resource without validating the user-supplied URI, letting attackers make it send requests to unexpected destinations. | Isolating resource-fetching mechanisms and strictly validating URIs against an allowlist. |
| API8: Security Misconfiguration | Vulnerability | A wide category covering misconfigured APIs or insecure defaults that attackers use to reach user data or system details. | Locking down and reviewing API configurations regularly, and avoiding default or overly complex setups that leave openings. |
| API9: Improper Inventory Management | Vulnerability | An incomplete inventory of hosts and deployed API versions leaves old versions or forgotten endpoints running and exposed. | Keeping complete documentation of your APIs, their endpoints, and how they store and share data with third parties. |
| API10: Unsafe Consumption of APIs | Vulnerability | Weaker validation and sanitization for data from third-party APIs lets attackers use those integrations for injection attacks, data exposure, and more. | Validating and sanitizing all data received from other APIs, and never blindly following redirects. |
Examples of API security errors
API risks can be subtle and hard to catch. To make it practical, here are a few API security issues Greptile flagged in real open source pull requests:
Missing access controls on indexed tickets (broken object level authorization)
A new Jira Service Management connector accepted a flag to sync permissions but never acted on it. As a result, every indexed ticket would have been visible to every user, regardless of their Jira project access.
An authorization check in the wrong order leaks admin status
A guard for instance-admin identities ran before the scoped lookup. An organization or project admin who submitted an out-of-scope ID would get an admin-specific 403 instead of a 404, revealing that the ID belonged to an instance admin.
A host override exposes an unauthenticated API (security misconfiguration)
Setting a host override to a non-loopback address would expose every unauthenticated read and write endpoint to anyone who could reach the port, letting them read, alter, or clear stored data.
7 best practices for API security
Managing API security is a large, ongoing project that requires regular checks and updates. Here are the best practices to start with:
- Encrypt all traffic
- Use strong authentication and authorization
- Validate and sanitize inputs
- Use rate limiting
- Manage secrets securely
- Log, monitor, and test API security
- Pair code review with runtime validation
1. Encrypt all traffic
Step one is encrypting all API traffic: internal, external, service-to-service, everything. This protects credentials, tokens, and data from being intercepted or tampered with in transit.
- Serve every API over HTTPS.
- Configure API clients to use HTTPS from the first request, and configure servers to reject plain HTTP rather than redirect it. A redirect teaches clients that HTTP works, and by the time a server rejects an HTTP request, any credentials in it have already crossed the network unencrypted.
- Use TLS 1.2 or higher for all external-facing APIs (NIST guidance sets TLS 1.2 as the minimum and calls for TLS 1.3 support [3]), and consider mutual TLS for service-to-service traffic.
- Disable older, outdated protocols and cipher suites.
2. Use strong authentication and authorization
Weak, improper, or missing authentication and authorization checks lead to a host of possible attacks. Four of the ten OWASP API risks (API1, API2, API3, and API5) are authentication or authorization failures, including the top three spots.
- Use OAuth 2.0, with JWT access tokens where they fit, as a well-established standard for production APIs, and follow the current OAuth security best practices [4].
- Use short-lived access tokens and store tokens securely.
- Use multi-factor authentication for users whenever possible, and check access at every layer: the object, its properties, the action, and the user's role.
- Don't treat an API key as user authentication on its own. A key identifies a client, not a person, so verify user identity and access level before acting on a request.
- Return the least amount of data possible. Avoid exposing anything an API call doesn't need to return.
3. Validate and sanitize inputs
Developers tend to trust data coming from third-party APIs more than standard user input. Don't. Doing so leads to weaker security measures and a larger surface for injection attacks and other vulnerabilities.
Instead, trust no one and nothing until you verify it.
- Always validate and sanitize data received from APIs before using it.
- Treat data from APIs with the same level of scrutiny as user input.
- Keep an allowlist of locations your APIs are allowed to redirect to, and never let your API endpoints blindly follow redirects from any source.
4. Use rate limiting
To prevent unrestricted resource consumption and abuse of sensitive business flows, implement rate limiting, throttling, and other limits that stop DoS and DDoS attacks.
- Consider every API endpoint and its risk to the business if it's used maliciously. Some endpoints could cause resource starvation, others could run up thousands of dollars in usage costs, and others could give attackers unrestricted access to business flows that affect sales, inventory, or resources.
- Set rate limits or throttling (time-based limits) based on each endpoint's sensitivity.
- Set spending or budget limits on usage-based third-party APIs where you can.
- Review every endpoint for limits on maximum allocable memory, number of processes, execution timeouts, how many times a client can repeat an operation, upload file size, records returned per page, and third-party spending.
5. Manage secrets securely
Poorly managed secrets create major API vulnerabilities, and they're an easy mistake to make. As your codebase grows, the number of API keys, tokens, and secrets grows with it, and it's easy to end up with "secrets sprawl."
- Never hardcode secrets. Use a dedicated secrets manager to keep API keys and other secrets safe.
- Rotate API keys, tokens, and other secrets on a regular schedule.
- Review code changes for exposed or insecure secrets, tokens, and API keys before they merge.
- Scope keys as narrowly as possible. If a key doesn't need to edit data, don't give it edit access; make it read-only.
6. Log, monitor, and test API security
Regular documentation, logging, testing, and updates are a must for API security. Without them, you run the risk of insecure endpoints, exposed access points, or vulnerabilities from outdated APIs, endpoints, or validation layers you don't know about. The bigger and more complex your codebase, the more this matters.
- Keep a regular inventory of API hosts, environments, network access, and endpoints. Document every role in the system, along with data flows and sensitivity.
- Document every aspect of each API: authentication, errors, redirects, rate limiting, endpoints, responses, and so on. Your logs should be able to tell you:
- Who accessed every API, and when
- Which endpoints they reached
- What results were returned
- What the authorization decision was (and whether it failed)
- Any failures or rate limits reached
- Any unusual patterns, requests, or anomalies (these often signal attacks or vulnerabilities that should be investigated right away)
- Follow each provider's own security guidance for the third-party APIs you integrate. For supported providers, Greptile's Partner Program reviews changes against partner-maintained docs, implementation rules, and common failure patterns.
- Regularly re-evaluate the risk and sensitivity of each API. Retire outdated or weak APIs, and tighten security wherever you can.
7. Pair code review with runtime validation
Some security vulnerabilities and API risks only show up when the code actually runs. Runtime validation helps you find them.
- Use a sandboxed, end-to-end runtime validation tool, like Greptile's TREX, which writes and runs targeted tests for a PR in an isolated sandbox to catch bugs that only appear when the code runs.
- Use mock data to test edge cases and confirm that user authentication, rate limiting, object-level authorization, and similar controls work in every case.
- Pair it with SCA scanning, like the dependency checks in Greptile's security review, to check the SDKs and packages you use to call third-party APIs against known vulnerability databases.
See more examples of API risks Greptile caught in open source repos:
- Auth bypass: Top-level IDs bypass authorization
- Security: Application tokens expose hidden workspace memberships
- Security: User consent bypass leaks query data to an untrusted RPC endpoint
How to test API security
You can't eliminate all vulnerabilities or risk from your code, so a 100% secure codebase isn't the goal.
Instead, the goal is to test regularly, understand what and where your risks are, and reduce the most critical ones to an acceptable level. (What counts as acceptable depends on your industry, compliance requirements, user data, and so on.)
Here's how we recommend managing ongoing API security testing:
- Inventory and document all API data and endpoints. You can't test what you can't find. If you're following the best practices above, you should already have up-to-date documentation of your API inventory. If not, that's ok: start here.
- Review and document expected inputs and outputs. What's supposed to happen with each API? What does it call, and what does it return? This gives you a baseline for what should be happening.
- Write and run tests in a controlled environment. All API testing should happen in an isolated, controlled sandbox environment with dummy data that doesn't expose real users, business logic, or data. Your tests should cover all three core areas of API security: authentication and authorization, vulnerabilities, and DoS/DDoS. Evaluate the results against your documented inputs and outputs.
Then, set up regular automated testing:
- Run static scans regularly (SAST and SCA). Pattern-based and rule-based SAST scanning can run on your codebase and on every new PR to find where vulnerabilities live in your code. SCA scanning checks third-party dependencies (like the SDKs and client libraries you use to call APIs) against known vulnerability databases. Running these checks early is a core part of shift-left testing. For example, Greptile's security review runs on every pull request to catch vulnerabilities before new code merges.
- Run dynamic testing (DAST). SAST reads the code; DAST puts it to the (literal) test. It maps your API surface (endpoints, parameters, and so on), then "attacks" those endpoints with broken or malicious data to see how the API holds up. It's a good way to find where your APIs are vulnerable and how to fix them.
- Run end-to-end tests in a sandbox for runtime validation. Sandbox testing, like Greptile's TREX, actually runs your code to catch errors that only show up at runtime. With TREX enabled, it runs as part of PR review, so you can catch vulnerabilities and fix them before the new code merges.
Automated API security testing: the key is context
Even if you haven't seen an API attack lately, the risks are getting harder to ignore. With the growth of agentic coding workflows, API vulnerabilities are easier to miss. AI coding assistants write code that touches dozens of files and third-party dependencies, often at a speed and scale that makes it hard for human developers to review well.
Automated security testing for APIs is the obvious answer. The key to making it work, without just adding more noise to your PR reviews or test suite, is context.
Many API security review and testing tools struggle here because they only see part of the picture. A scanner that reads one file or one diff at a time can't tell where data comes from, where it goes, how each piece of your codebase fits together, or what a change touches. On a large or messy codebase, your human devs can't hold all of that in their heads either.
Without a code review tool that can pick up the slack, you won't have the full picture of the API security issues that might be hiding in your codebase.
Beyond that, API security requires end-to-end testing that actually runs the code and sees what it does, not just what it looks like it might do. (For a side-by-side look at tools in this space, see our guide to the best security-focused code review tools.)
Greptile is built to fill these gaps in your code review and security process:
- Greptile understands the full context of your codebase. Greptile documents how each part of your codebase works and how it connects to everything else, and keeps a running list of past bugs and potential risks.
- Built-in security review checks every PR. Opengrep rule-based scanning pattern-matches for dangerous code constructs, and SCA checks your dependencies against known vulnerability databases.
- AI-powered security checks review changes in the context of your codebase. An AI security agent catches chained exploits and issues static tools can miss, like authorization bypasses, filesystem and PATH attacks, denial of service, and security-gate bypasses.
- TREX runs the code. TREX installs your dependencies, starts the services a change touches, and exercises the code with targeted tests in a sandbox. When a run fails, it leaves a PR comment with logs, screenshots, traces, or API output attached, so authentication, authorization, resource limit, and other errors can be caught before they reach prod.
- Partner-maintained context checks your third-party integrations. When a PR touches a supported partner's API, SDK, or config, Greptile reviews the change against that partner's docs, implementation rules, and common failure patterns.
This is how teams like Podium review 8,400+ code changes per week while catching small, critical errors, like a configuration issue that would have caused deployment failures.
“Greptile frequently exposes missed items during code reviews. This has increased our deployment and code quality delivered in general.
”
Ready to add context-aware security review and runtime validation to your API workflow? Try Greptile free for 14 days and see what it catches on your team's PRs →
Sources
[1] OWASP API Security Project. "Foreword." OWASP Top 10 API Security Risks, 2023. api-security.owasp.org/editions/2023/en/0x02-foreword
[2] OWASP API Security Project. "OWASP Top 10 API Security Risks – 2023." api-security.owasp.org/editions/2023/en/0x11-t10
[3] NIST. "SP 800-52 Rev. 2, Guidelines for the Selection, Configuration, and Use of Transport Layer Security (TLS) Implementations." csrc.nist.gov/pubs/sp/800/52/r2/final
[4] IETF. "RFC 9700: Best Current Practice for OAuth 2.0 Security." rfc-editor.org/rfc/rfc9700