Cybersecurity

How to Secure Your APIs: Best Practices

November 18, 2026 · 10 min read

How to Secure Your APIs: Best Practices

APIs are the backbone of modern software. They connect your mobile app to its backend, your website to payment providers, your systems to partners and, increasingly, your data to AI agents. That makes them one of the most attractive targets for attackers, because a single weak endpoint can expose an entire database. Following API security best practices is now essential for every development team, not just large enterprises.

This guide explains the most common API vulnerabilities based on the OWASP API Security Top 10, then walks through 15 practical best practices with a complete Node.js example that shows authentication, validation, rate limiting and authorisation working together.

Why API Security Matters

APIs expose business logic and data directly, often without the protections a user interface provides. Attackers do not need to click through your app; they call your endpoints directly, change IDs, send unexpected data and automate requests at scale. Leaked API keys add to the risk: GitGuardian's State of Secrets Sprawl 2026 report found 28.65 million new hardcoded secrets in public GitHub commits in 2025, with leaks of secrets for AI services growing especially fast, according to the GitGuardian report.

Web application risks and API risks overlap. Broken access control, which includes the API flaw known as broken object level authorisation, is ranked first in the OWASP Top 10:2025.

The OWASP API Security Top 10

The OWASP API Security Project publishes a dedicated list of API risks. The current edition, released in 2023, includes:

RiskWhat It Means
API1: Broken Object Level AuthorizationUsers can access other users' records by changing an ID
API2: Broken AuthenticationWeak login, token or session handling
API3: Broken Object Property Level AuthorizationExposing or allowing changes to fields users should not see or edit
API4: Unrestricted Resource ConsumptionNo limits on requests, payload sizes or expensive operations
API5: Broken Function Level AuthorizationRegular users can call admin functions
API6: Unrestricted Access to Sensitive Business FlowsAutomated abuse of flows such as sign-ups, bookings or purchases
API7: Server Side Request ForgeryThe API can be tricked into requesting internal resources
API8: Security MisconfigurationUnsafe defaults, verbose errors and open CORS settings
API9: Improper Inventory ManagementForgotten old versions and undocumented endpoints
API10: Unsafe Consumption of APIsBlindly trusting data from third-party APIs

15 API Security Best Practices

1. Use strong, standard authentication

Use proven standards such as OAuth 2.0 and OpenID Connect through a trusted identity provider. Issue short-lived access tokens, validate their signature, issuer, audience and expiry on every request, and never invent your own token scheme.

2. Check authorisation on every object

Broken object level authorisation is the most common and most damaging API flaw. For every request that uses an ID, confirm that the authenticated user is allowed to access that specific record. Return "not found" rather than "forbidden" to avoid revealing which IDs exist.

3. Check permissions for every function

Protect admin and internal endpoints with role checks on the server. Hiding a button in the user interface is not access control.

4. Return only the data clients need

Never return whole database objects. Explicitly choose response fields, and block mass assignment by accepting only the fields a user may change, so nobody can update fields such as role or price.

5. Validate all input

Validate request bodies, parameters and headers against strict schemas: types, lengths, ranges and allowed values. Reject everything else. Libraries such as Zod, Joi or JSON Schema make this straightforward.

6. Apply rate limits and quotas

Limit requests per user, IP address and API key, cap payload sizes and paginate large results. Rate limiting protects against brute-force attacks, scraping, denial of service and runaway costs.

7. Encrypt everything in transit

Serve APIs only over HTTPS with modern TLS, and never accept tokens or keys over plain HTTP.

8. Protect API keys and secrets

Keep keys out of code, mobile apps and front-end bundles. Store them in a secrets manager, scope them to the minimum permissions, rotate them regularly and revoke any key that leaks.

9. Use an API gateway

An API gateway centralises authentication, rate limiting, logging and request filtering, so every service benefits from consistent protection.

10. Keep an inventory of your APIs

Document every API, version and environment. Retire old versions, remove test endpoints from production and make sure nothing is exposed that nobody owns.

11. Handle errors safely

Return generic error messages to clients and log details privately. Stack traces and database errors help attackers map your system.

12. Log and monitor API activity

Log authentication failures, authorisation denials, unusual request rates and access to sensitive data, without logging passwords or tokens. Alert on patterns such as one user requesting thousands of different IDs.

13. Prevent server-side request forgery

If your API fetches URLs supplied by users, such as for webhooks or image imports, restrict destinations with allow lists and block internal network addresses.

14. Treat third-party APIs as untrusted

Validate data returned by partners and external services, set timeouts and handle failures gracefully, because a compromised supplier can become your attacker.

15. Test security continuously

Add automated security tests for authorisation, run dependency and secret scans in your pipeline, and include APIs in regular penetration tests. Our guide on how to run an application security audit explains what to test.

Example: A Secure API Endpoint in Node.js

This Express route combines authentication with signed tokens, rate limiting, schema validation, an object-level ownership check and a minimal response:

// orders-api.mjs: an Express route with authentication, rate limiting,
// input validation and an object-level authorisation check
import express from "express";
import rateLimit from "express-rate-limit";
import { jwtVerify, createRemoteJWKSet } from "jose";
import { z } from "zod";
import { db } from "./db.mjs";

const app = express();
app.use(express.json({ limit: "100kb" }));
app.use(rateLimit({ windowMs: 60 * 1000, limit: 100 }));

const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

// 1. Authentication: verify the access token on every request
async function authenticate(req, res, next) {
  try {
    const token = req.headers.authorization?.replace("Bearer ", "");
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: "https://auth.example.com/",
      audience: "orders-api",
    });
    req.user = { id: payload.sub, role: payload.role };
    next();
  } catch {
    res.status(401).json({ error: "Unauthorised" });
  }
}

const updateSchema = z.object({
  quantity: z.number().int().min(1).max(100),
});

app.patch("/orders/:id", authenticate, async (req, res) => {
  // 2. Validation: reject anything that does not match the schema
  const parsed = updateSchema.safeParse(req.body);
  if (!parsed.success) return res.status(400).json({ error: "Invalid input" });

  // 3. Object-level authorisation: users may only change their own orders
  const order = await db.orders.findById(req.params.id);
  if (!order || order.userId !== req.user.id) {
    return res.status(404).json({ error: "Not found" });
  }

  const updated = await db.orders.update(order.id, { quantity: parsed.data.quantity });

  // 4. Return only the fields the client needs
  res.json({ id: updated.id, quantity: updated.quantity, status: updated.status });
});

app.listen(3000);

Every request must carry a valid token, oversized or malformed input is rejected, users can only change their own orders, and the response exposes only safe fields. The same principles apply in any language or framework.

API Security for Mobile Apps

Mobile apps can be downloaded and reverse-engineered, so anything inside them, including API keys and hidden endpoints, should be considered public. Authenticate users rather than apps, keep secrets on the server, use certificate validation correctly and protect sensitive actions with step-up authentication. Our guides to mobile app security best practices and two-factor authentication cover these topics in depth.

APIs, AI Agents and Zero Trust

AI agents and integrations increasingly call APIs on behalf of users. Give each agent or integration its own credentials with narrowly scoped permissions, log what it does and require human approval for sensitive actions. This fits naturally with a zero trust security approach, where every request is verified regardless of where it comes from. If you are adding AI to your product, our guide on how to add ChatGPT or Claude to your website explains how to keep AI API keys safe on the server.

REST, GraphQL and Webhook Security

  • REST APIs: apply the practices above to every route, and pay special attention to IDs in URLs, which are the usual target of object-level authorisation attacks.
  • GraphQL APIs: a single endpoint can expose your whole data graph, so enforce authorisation in resolvers, limit query depth and complexity, disable introspection in production if you do not need it, and rate-limit by query cost rather than request count.
  • Webhooks: verify signatures on incoming webhooks from payment providers and other services, reject old timestamps to prevent replay attacks, and process events idempotently so duplicates do no harm.
  • Internal service-to-service APIs: authenticate services with their own short-lived credentials or mutual TLS rather than trusting the network.

Common API Security Mistakes

  • Checking that a user is logged in, but not that they own the record they requested
  • Returning full database objects, including internal fields and other users' data
  • Leaving old API versions running long after the app stopped using them
  • Putting secret keys in mobile apps or front-end JavaScript
  • Allowing unlimited page sizes, file uploads or expensive queries
  • Using permissive CORS settings that allow any website to call the API with user credentials

API Security Checklist

Before LaunchOngoing
Authentication on every endpointRotate keys and review scopes
Object and function level authorisation testsMonitor logs and alerts
Input validation and payload limitsPatch dependencies promptly
Rate limiting and quotasRetire old API versions
HTTPS only, safe error messagesRegular security testing
API inventory and documentationReview third-party integrations

Many API weaknesses are variations of the issues in our guide to the most common security mistakes in software projects.

Frequently Asked Questions

What is the most common API vulnerability?

Broken object level authorisation, where users can access other users' data by changing an ID in the request. It is the first entry in the OWASP API Security Top 10.

Are API keys enough to secure an API?

No. API keys identify an application, not a user, and they are easily leaked. Use user authentication with short-lived tokens, plus authorisation checks, for anything sensitive.

What is the difference between authentication and authorisation?

Authentication confirms who is making the request. Authorisation decides what that user is allowed to do. APIs need both on every request.

How do I protect my API from abuse?

Use rate limiting, quotas, payload size limits, pagination, bot detection for sensitive flows and monitoring that alerts you to unusual patterns.

Should internal APIs be secured too?

Yes. Attackers who get inside your network or cloud account will target internal APIs. Apply authentication, authorisation and encryption to internal services as well.

How often should APIs be security tested?

Run automated tests on every change, scan dependencies continuously and include APIs in a professional security assessment at least once a year or before major releases.

Conclusion

Following API security best practices comes down to a few core habits: authenticate every request, authorise every object and function, validate every input, limit every client, protect every secret and monitor everything. Build these into your framework and templates so every new endpoint is secure by default, and test them continuously as your API grows.

Need a secure API for your web or mobile app? Our team designs, builds and reviews APIs with security built in from day one. Contact us for an API security review.

Want this built for you?

Our team offers Website Deploy On Vercel — get a free quote.

View Services