Skip to main content
REST API Design Tutorial
CHAPTER 11 Beginner

API Security Best Practices

Updated: May 14, 2026
30 min read

# CHAPTER 11

API Security Best Practices

1. Introduction

Building an API is only half the battle; defending it is the other half. Because APIs are specifically designed to accept raw data payloads from external sources, they are the primary target for automated hacking scripts. A single vulnerability can expose your entire database or bring your servers offline. In this chapter, we will explore the mandatory environmental defenses required for production APIs, including HTTPS, Rate Limiting, CORS, and comprehensive input sanitization.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain why HTTPS is non-negotiable for REST APIs.
  • Understand how CORS prevents malicious cross-origin attacks.
  • Implement Rate Limiting to mitigate Brute Force and DDoS attacks.
  • Differentiate between Input Validation and Input Sanitization.
  • Identify the principles of Data Exposure prevention.

3. Beginner-Friendly Explanation

Imagine your API is a highly secure vault.
  • HTTPS: You build a concrete tunnel between the customer and the vault. No one outside the tunnel can see what the customer is carrying.
  • CORS: You check the customer's ID to ensure they are coming from a trusted partner building, not a random location.
  • Rate Limiting: If a customer tries 10,000 vault combinations in 5 seconds, you activate a trapdoor and lock them out for 15 minutes.
  • Sanitization: Before the customer puts their box in the vault, you scan the box to ensure it doesn't contain a bomb (malicious SQL code).

4. Defense 1: Mandatory HTTPS (TLS)

HTTPS (Hypertext Transfer Protocol Secure) encrypts the entire connection between the Client and the API Server. If an API accepts a JWT token or an API Key over plain http://, the token is transmitted in plain, readable text. Anyone on the user's public Wi-Fi network can intercept the network packet, steal the token, and hijack the account instantly. Rule: A production API must *never* answer an HTTP request. It must forcibly redirect all traffic to HTTPS using an SSL/TLS Certificate.

5. Defense 2: Rate Limiting

APIs are vulnerable to DDoS (Distributed Denial of Service) and Brute Force password attacks. You must restrict how many times a single IP address can hit your API within a specific timeframe.

Implementation (Express.js):

javascript
123456789101112
const rateLimit = require('express-rate-limit');

// Define the rule: Max 100 requests per 15 minutes per IP
const globalLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, 
    max: 100,
    message: "Too many requests from this IP, please try again after 15 minutes",
    headers: true, // Sends X-RateLimit headers to the client
});

// Apply globally to all API routes
app.use('/api/', globalLimiter);

*(When the limit is exceeded, the API automatically returns HTTP 429 Too Many Requests).*

6. Defense 3: CORS (Cross-Origin Resource Sharing)

If your API is hosted at api.example.com and your React frontend is at app.example.com, modern web browsers will violently block the React app from reading the API's data. This is a built-in browser security mechanism to stop a malicious site (hacker.com) from making requests to your API on behalf of a victim user.

To fix this, you must configure CORS on your backend. You explicitly whitelist your trusted frontend domain.

Implementation (Express.js):

javascript
12345678910
const cors = require('cors');

// Whitelist specific domains
const corsOptions = {
    origin: 'https://app.example.com',
    optionsSuccessStatus: 200
};

// Apply CORS middleware
app.use(cors(corsOptions));

*(Now, the API will add Access-Control-Allow-Origin: https://app.example.com to its HTTP Headers, and the browser will allow the request).*

7. Defense 4: Input Sanitization

Validation (Chapter 9) ensures the data is the correct *type* (e.g., a string). Sanitization ensures the data is *safe*.

If a user submits a blog comment: <script>alert('Hacked!');</script>, and your API saves it directly to the database, you have created a severe Cross-Site Scripting (XSS) vulnerability. When other users load the comments, their browsers will execute that malicious Javascript.

Rule: Always strip dangerous HTML tags from incoming strings before saving them to the database. Libraries like DOMPurify or specific sanitization middleware will convert <script> into harmless encoded text (&lt;script&gt;).

8. Defense 5: Preventing Data Exposure

A massive mistake beginners make is returning entire database rows from the API.
javascript
12345
// DANGEROUS!
app.get(&#039;/api/users/1&#039;, async (req, res) => {
    const user = await database.getUser(1);
    res.json(user); // Leaks password_hash, reset_tokens, internal IDs!
});

Rule: As discussed in Chapter 8, ALWAYS use an API Resource, Serializer, or Data Transfer Object (DTO) to explicitly map and filter exactly which database columns are allowed to be sent to the public.

9. Best Practices

  • Helmet.js: In Node.js, always install and use the helmet package. It automatically configures dozens of obscure HTTP security headers (like HSTS, X-Frame-Options, and Content Security Policies) that protect your API against common web vulnerabilities with just one line of code: app.use(helmet());

10. Common Mistakes

  • CORS Origin: * in Production: Setting your CORS origin to * (Wildcard) means "Allow any website on the internet to call this API." While this is fine for public, read-only APIs (like a weather API), it is disastrous for private APIs containing user data. Always explicitly define your trusted frontend URLs in your CORS configuration.

11. Exercises

  1. 1. Define the purpose of Rate Limiting. Which specific HTTP Status code is returned when a client triggers the rate limiter?

12. Coding Challenges

  • Challenge: You are architecting a highly secure login endpoint at POST /api/login. Should you apply the global rate limit (100 requests / 15 mins) to this specific route, or should you create a separate, much stricter rate limiter (e.g., 5 requests / 15 mins) just for the login route? Explain your reasoning in terms of Brute Force mitigation.

13. MCQs with Answers

Question 1

Why is it a critical security vulnerability to transmit an API Key or JWT over a plain HTTP connection?

Question 2

Which backend security configuration explicitly instructs web browsers whether they are allowed to permit frontend JavaScript applications on different domains to access the API's resources?

14. Interview Questions

  • Q: Explain the difference between Input Validation and Input Sanitization. Provide a concrete example of a Cross-Site Scripting (XSS) vulnerability that occurs when sanitization is skipped on a text input field.
  • Q: Walk me through the mechanics of CORS. Why do web browsers enforce the Same-Origin Policy, and how does the backend API explicitly override this policy to allow a trusted React frontend to consume its data?

15. FAQs

Q: Do I need CORS if I am building a mobile app (iOS/Android)? A: Surprisingly, no! CORS is strictly a *web browser* security feature. Native mobile apps do not run inside browsers, so they do not enforce CORS policies. However, if your API serves both a mobile app and a web app, you must configure CORS for the web app's sake.

16. Summary

In Chapter 11, we locked down our API environment. We established that HTTPS encryption is non-negotiable for protecting data in transit. We implemented strict Rate Limiting to defend against automated DDoS and Brute Force attacks. We demystified the frustrating CORS browser errors by explicitly whitelisting trusted frontend domains. Finally, we emphasized the absolute necessity of Input Sanitization to prevent database corruption and XSS attacks, ensuring our API is hardened against malicious intent.

17. Next Chapter Recommendation

Our API is secure, but what happens when a database query returns 10,000 records at once? Proceed to Chapter 12: Pagination, Filtering, and Sorting.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·