API Security Guide: Architecture, Risks, and Best Practices
API7.ai
July 13, 2026
Introduction
API security is a lifecycle discipline for protecting APIs, their data, and the services behind them. It spans the full API lifecycle: teams must know which APIs exist, design appropriate trust boundaries, authenticate callers, authorize individual actions, control traffic, detect abuse, and respond when behavior departs from expectations. As part of a broader API infrastructure architecture, security works alongside gateway traffic controls, governance, and observability.
This guide is for developers, platform engineers, security engineers, architects, and technical leaders responsible for APIs in distributed systems. It explains the major API security risks, how a layered security architecture works, where an API gateway fits, and how to build repeatable security practices without turning every service team into a security specialist.
API security is not a single plugin or protocol. OAuth, JSON Web Tokens (JWTs), mutual TLS (mTLS), API keys, schema validation, rate limiting, and threat detection each solve different parts of the problem. Effective protection comes from combining them according to the API's consumers, data sensitivity, runtime environment, and business impact. The related API governance practices and API observability practices provide the operating context for those controls.
What Is API Security?
API security protects the confidentiality, integrity, and availability of API interactions. It also protects the business operations exposed through an API, such as transferring funds, changing account permissions, or submitting a high-value order. This makes security a core concern in API management, not only an edge-runtime configuration task.
A complete program addresses four questions:
- What is exposed? Maintain an accurate inventory of APIs, versions, owners, environments, and data classifications.
- Who or what is calling? Authenticate users, applications, workloads, and partner systems with credentials appropriate to the trust model.
- What may the caller do? Authorize access at the API, operation, object, and property levels.
- Is the behavior acceptable? Enforce traffic and validation policies, observe usage, detect abuse, and respond to incidents.
For a foundation in the first two controls, read Authentication vs Authorization in APIs. For the broader API landscape, begin with API 101.
Why API Security Matters
Modern APIs connect public applications, internal services, partners, mobile clients, automation, and third-party systems. This connectivity expands the useful surface of a platform, but it also creates more paths to sensitive data and business operations. In microservices architectures, the number of owners and service boundaries can make consistent protection harder to maintain.
Several characteristics make API security distinct from conventional web security:
- APIs expose structured data and actions directly, so a valid request can still access the wrong object or perform an unauthorized function.
- Machine clients send requests at high volume, making credential abuse, scraping, and resource exhaustion difficult to distinguish from legitimate automation without context.
- Microservices and cloud-native deployments distribute ownership across teams and environments, increasing the risk of inconsistent controls and forgotten endpoints.
- APIs evolve through versions and deployments. An old or undocumented API can remain reachable after the owning team has moved on.
- Third-party integrations extend the trust boundary. An API can securely process a request while still consuming unsafe upstream data or relying on a compromised dependency.
The OWASP API Security Top 10 provides a useful risk vocabulary, including broken object-level authorization, broken authentication, unrestricted resource consumption, security misconfiguration, improper inventory management, and unsafe consumption of APIs. Teams should use it as a risk model, not as a one-time compliance checklist.
API Security Architecture
Layered API security places controls at the points where they have the right context. Identity systems establish caller identity. The gateway applies shared runtime controls. Services enforce domain-specific authorization. API observability and security operations correlate events across the environment.
flowchart LR client[Users, Apps, and Workloads] --> edge[Edge and Network Controls] edge --> gateway[API Gateway Runtime] gateway --> service[Backend Services] identity[Identity Provider] --> gateway identity --> service policy[Central Policy and Secrets] --> gateway policy --> service gateway --> telemetry[Security Logs, Metrics, and Traces] service --> telemetry telemetry --> response[Detection and Incident Response]
Identity and Credential Layer
An identity provider issues or validates credentials for users and workloads. The credential type should match the use case:
- OAuth 2.0 and OpenID Connect (OIDC) support delegated access and user identity flows.
- JWTs carry signed claims that a gateway or service can validate, but validation must include the signature, issuer, audience, expiration, and accepted algorithms.
- mTLS authenticates both sides of a connection and is useful for service-to-service and partner trust relationships.
- API keys identify an application or consumer but usually do not represent a user or provide granular authorization by themselves.
- HMAC signatures can protect request integrity and authenticate clients when both parties securely manage shared secrets.
See API Gateway Authentication with OAuth, JWT, and OIDC and API Security with mTLS and HMAC for implementation context.
Gateway Runtime Layer
An API gateway is a controlled entry point for API traffic. It can centralize policies that should be consistent across services:
- Validate tokens and client credentials.
- Apply coarse-grained access rules.
- Enforce rate, concurrency, and request-size limits.
- Validate methods, hosts, paths, headers, and request schemas.
- Restrict origins and manage cross-origin resource sharing (CORS).
- Terminate or pass through TLS according to the architecture.
- Record security-relevant request metadata.
- Block known malicious patterns or integrate with external security controls.
The gateway reduces duplicated enforcement, but it cannot understand every domain rule. A gateway may know that a token has an orders:read scope; the order service must still verify that the caller may access the requested order.
Service Authorization Layer
Backend services enforce decisions that depend on business data and application state. This includes object-level, function-level, and property-level authorization. Teams should make these checks explicit and test denial paths as carefully as successful paths.
Do not treat possession of a valid token as permission to access every object behind an endpoint. Validate the relationship between the authenticated subject, the requested operation, and the resource on every relevant request.
Detection and Response Layer
Security controls need feedback. Logs should capture authentication outcomes, policy decisions, administrative changes, and unusual access without exposing secrets or sensitive payloads. Metrics can reveal spikes in denied requests, token failures, latency, or resource consumption. Distributed traces can help responders follow a suspicious request across services.
Connect these signals to ownership and response workflows. An alert without an API owner, service context, or remediation path is unlikely to reduce risk.
Common API Security Risks
Broken Authorization
Broken authorization occurs when a caller can act on an object, field, or function that should be inaccessible. Common causes include trusting a user-supplied identifier, checking only the role but not resource ownership, and exposing administrative functions through predictable endpoints.
Mitigations include deny-by-default policy, server-side authorization on every request, opaque or non-sequential identifiers as defense in depth, and automated tests that attempt cross-account and cross-role access.
Broken Authentication and Credential Abuse
Weak token validation, long-lived credentials, leaked API keys, insecure password recovery, and missing brute-force protection can let attackers impersonate legitimate callers. Centralize validation rules where practical, rotate secrets, use short-lived credentials, and bind tokens to the correct issuer and audience.
Resource Exhaustion and Automated Abuse
APIs can be abused through high request volume, expensive queries, oversized payloads, or repeated business actions such as account creation and inventory reservation. Rate limiting is necessary, but limits should reflect consumer identity, operation cost, and business semantics rather than only source IP.
For runtime patterns, see Rate Limiting and Throttling.
Injection and Unsafe Input
Structured API payloads still contain untrusted input. Validate schemas, enforce content types and size limits, use parameterized data access, and encode output for its destination. Do not pass client-controlled URLs, headers, or query fragments to internal services without allowlists and validation.
Misconfiguration and Improper Inventory
Permissive CORS, default credentials, verbose errors, exposed administrative routes, inconsistent TLS, and forgotten API versions are common operational risks. Maintain a catalog tied to ownership and deployment data, and continuously compare the expected API surface with what is actually reachable.
Unsafe Third-Party API Consumption
Treat responses from partner and third-party APIs as untrusted input. Validate data, set connection and response limits, handle redirects deliberately, and isolate credentials. A trusted vendor relationship does not make every response safe for downstream processing.
API Security Across the Lifecycle
Security becomes more reliable when it is part of normal API delivery rather than a review at the end. Connect these practices to the API lifecycle so ownership, testing, deployment, and incident response stay visible as APIs change.
flowchart LR inventory[Inventory and Ownership] --> design[Threat Model and Secure Design] design --> build[Implementation and Automated Tests] build --> deploy[Policy and Configuration Validation] deploy --> operate[Runtime Protection and Observability] operate --> improve[Incident Learning and Improvement] improve --> inventory
Plan and Design
Identify the API owner, consumers, data sensitivity, trust boundaries, abuse cases, and availability requirements. Define authentication and authorization before implementation. Document which decisions belong at the gateway and which require service context.
Build and Test
Use secure libraries for cryptography and token processing. Add negative tests for missing, expired, malformed, and incorrectly scoped credentials. Test object ownership, role boundaries, payload limits, and unexpected content types. Include API definitions and policy configuration in review workflows.
Deploy
Separate credentials and policies by environment. Validate gateway routes, TLS, exposed ports, administrative APIs, and default settings. Use least privilege for deployment automation and control-plane access. Avoid copying production secrets into development systems.
Operate
Monitor authentication failures, authorization denials, policy changes, traffic anomalies, and resource consumption. Keep API inventory synchronized with deployment data. Rotate credentials and remove deprecated routes. Review whether controls still match actual consumer behavior.
Respond and Improve
Incident plans should cover credential revocation, route isolation, rate-limit changes, evidence preservation, consumer communication, and safe restoration. Feed findings back into threat models, tests, policies, and ownership records.
API Security Best Practices
Use Defense in Depth
Combine network controls, identity, gateway policy, service authorization, data protection, and observability. Avoid assuming that an internal network or a single authenticated hop is inherently trusted.
Separate Authentication from Authorization
Authentication establishes identity; authorization decides whether that identity can perform a specific action. Keep the distinction clear in architecture, code, logs, and ownership. A valid identity can still be unauthorized.
Apply Least Privilege
Issue narrow scopes and permissions, use short credential lifetimes where possible, and limit administrative access. Review permissions when services, teams, and partner relationships change.
Standardize Shared Controls
Platform teams can provide approved authentication patterns, gateway policy templates, secret-management integrations, and secure defaults. Service teams remain responsible for domain authorization and data handling. This division reduces inconsistency while preserving application context.
Protect Secrets and Sensitive Data
Do not place secrets in source code, URLs, logs, or client-visible errors. Encrypt data in transit, manage keys and certificates through controlled systems, and minimize collection of sensitive payloads in telemetry.
Control Resource Use
Set limits for request rate, concurrency, payload size, processing time, and expensive operations. Test how the system fails when dependencies slow down or limits are reached.
Maintain an Accurate API Inventory
Track owners, versions, environments, exposure, consumers, and retirement dates. Inventory should be connected to deployment and gateway configuration where possible, not maintained as an isolated spreadsheet.
Test Continuously
Combine unit and integration tests, API schema validation, dependency scanning, configuration checks, and targeted security testing. Re-test after authorization, routing, identity, or data-model changes.
API Security Learning Paths
Use these paths to move from identity fundamentals to runtime enforcement, validation, and ongoing security operations. Each resource focuses on a narrower implementation or risk area covered by this guide.
Start with Identity and Access
- API Access vs Authentication vs Authorization
- Authentication vs Authorization in APIs
- Implementing JWT for API Security
- OAuth 2.0 for Secure API Access
- API Key Management Best Practices
- API Gateway Authentication with OAuth, JWT, and OIDC
Protect Transport and Secrets
- API Security with mTLS and HMAC
- Data Encryption in API Communication
- HashiCorp Vault and Apache APISIX
Build Runtime Protection
- API Gateway Guide
- Rate Limiting and Throttling
- Protect Against the OWASP API Security Top 10
- WAF and API Gateway Integration
- Protecting APIs Against DDoS Attacks
- Why Least Privilege Reduces Security Risk
Test and Validate APIs
- API Security Testing Tools and Techniques
- Security Testing for APIs
- Avoiding Common API Vulnerabilities
- Understanding CORS in APIs
Operationalize Security
How API7 and Apache APISIX Fit
Apache APISIX is an open source API gateway that provides runtime plugins for authentication, traffic control, request validation, logging, and integrations with security systems. It can serve as the enforcement layer in a broader API security architecture.
API7 Enterprise adds centralized API and gateway management for organizations operating multiple teams and environments. The Zero Trust Security solution describes relevant API7 capabilities for identity integration, encrypted communication, access control, and policy enforcement.
The gateway should remain one layer in the design. Pair runtime enforcement with service-level authorization, secure development practices, accurate inventory, observability, and incident response.
Recommended Next Steps
- Establish the fundamentals in API 101.
- Understand the runtime layer in the API Gateway Guide.
- Define shared ownership and policy in the API Governance Guide.
- Build operational visibility with the API Observability Guide.
- Explore the wider ecosystem in the API Infrastructure Guide.