# How to Secure a REST API?

> Securing a REST API in practice — HTTPS/TLS, authentication, input validation, CORS, rate limiting, and avoiding information disclosure.

> 💡 **Summary (TL;DR):**
> - **Why it Matters:** REST APIs are entry points to your application. A poorly configured API is an invitation for data breaches, unauthorized access, and DDoS attacks.
> - **Core Security Layers:** HTTPS (encryption), authorization (OAuth2/JWT), input validation (preventing XSS/SQLi), CORS configuration, and Rate Limiting.
> - **Reference:** You should align your security architecture with the **OWASP API Security Top 10** standards.

This article is part of the **RESTful API Design** series. If you haven't read the previous articles in the series, I highly recommend starting there:

- [REST Api Design: Principles and Output Format](/rest-api-design)
- [What Should the REST API URI Structure Be?](/rest-api-uri-structure)
- [What is HATEOAS in REST API?](/what-is-hateoas)
- [How to Perform REST API Authentication?](/rest-api-authentication)
- [How to Perform REST API Error Handling?](/rest-api-error-handling)

---

## 1. Transport Layer Security: HTTPS and TLS

The first and most non-negotiable step in REST API security is utilizing the **HTTPS** protocol. A production-ready REST API must run exclusively over HTTPS. 

Using HTTP is like locking your front door while leaving all your windows wide open. Unencrypted HTTP traffic can be intercepted by anyone on the network path (Man-in-the-Middle or MitM attacks). HTTPS encrypts all traffic between the client and server using TLS (Transport Layer Security). 

> 🔒 **Extra Security:** Simply using HTTPS is not enough. You should disable outdated SSL and weak TLS versions (TLS 1.0 and 1.1) on your API server and enforce modern, secure protocols like **TLS 1.2 and TLS 1.3**.

---

## 2. Authentication and Authorization (AuthN & AuthZ)

If your API is not public, you must verify who is making each request (Authentication) and ensure they have permission to perform the requested action (Authorization).

- **JWT (JSON Web Token):** Highly popular for stateless APIs. However, when using JWT, prefer secure asymmetric algorithms like **RS256** to sign tokens, and keep the expiration time short.
- **OAuth 2.0:** The industry standard for enabling secure, scoped access to user data by third-party applications.
- **API Keys:** Suitable for simple machine-to-machine communication. However, API keys must be passed in HTTP headers (e.g., `X-API-Key`) rather than URL query parameters.

For a deeper dive into authentication methods, see the dedicated article in this series:  
👉 [How to Perform REST API Authentication?](/rest-api-authentication)

---

## 3. Input Validation and Sanitization

You should **never trust** data coming from the client. All inputs entering your API—including URL parameters, query strings, the HTTP request body, and headers—must undergo strict validation on the server.

- **SQL Injection (SQLi):** Always use prepared statements or Object-Relational Mappers (ORMs) instead of executing raw, concatenated SQL strings.
- **XSS (Cross-Site Scripting):** Sanitize input to strip or escape HTML tags and Javascript scripts.
- **Request Size Limiting:** Enforce a maximum request size (e.g., 1MB or 10MB) to prevent attackers from exhausting server memory (RAM) by uploading massive payloads.

*Example of Secure Database Querying in PHP using PDO:*
```php
// Bad & Vulnerable Method (Prone to SQL Injection)
$input = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$input'"; 

// Correct & Secure Method (Prepared Statement)
$statement = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$statement->execute(['username' => $_GET['username']]);
$user = $statement->fetch();
```

---

## 4. CORS (Cross-Origin Resource Sharing) Configuration

CORS is a security mechanism enforced by web browsers that controls whether web apps hosted on other origins (domains) are allowed to make requests to your API.

Many developers use `Access-Control-Allow-Origin: *` to make things work quickly. However, for APIs containing sensitive data or requiring authentication, this wildcard is a major security vulnerability. You should explicitly define the allowed origin domains and properly configure the access parameters for credentials (cookies/Authorization headers).

---

## 5. Rate Limiting

Limiting request volume at the server or application level protects your API from brute-force and DDoS attacks. It also prevents resource starvation caused by abusive clients.

To help client applications play nicely with these limits, include informative headers in your HTTP responses:

```http
X-Rate-Limit-Limit: 1000      # Max requests allowed in the current window
X-Rate-Limit-Remaining: 985   # Remaining requests in the current window
X-Rate-Limit-Reset: 16200000  # Unix timestamp when the limit resets
```

When a client exceeds the limit, the API should return a standard **`429 Too Many Requests`** HTTP status code.

---

## 6. Error Handling and Information Disclosure

When managing errors, you must strike a balance between providing helpful details to developers and leaking sensitive system details to attackers. Never expose database schemas, stack traces, or server version strings in public error payloads.

- ❌ **Incorrect:** `Database Connection Error: Access denied for user 'admin'@'10.0.0.5' (using password: YES)`
- **Correct:** `Internal Server Error. Please contact support with request ID: #98231`

---

## 7. Web Application Firewall (WAF) Usage

While implementing security measures in your code is essential, filtering out attacks like SQL Injection, XSS, and DDoS before they reach your application server is much more efficient. Cloud-based WAFs (such as Cloudflare or AWS WAF) or server-level modules (like ModSecurity) analyze and filter malicious requests at the edge, reducing server load and preventing exploit attempts.

---

## Security Methods Comparison

| Security Layer | Prevented Attack | Difficulty | Cost / Performance Impact |
| :--- | :--- | :--- | :--- |
| **HTTPS (TLS 1.3)** | MitM (Man-in-the-Middle), Eavesdropping | Low | Negligible (trivial for modern CPUs) |
| **Rate Limiting** | DDoS, Brute Force, Resource Exploitation | Medium | Low (easily handled with Redis/Memcached) |
| **Input Validation** | SQL Injection, XSS, Buffer Overflow | High (requires ongoing maintenance) | None (minimal CPU processing) |
| **CORS Config** | CSRF, Unauthorized Browser Requests | Low | None |
| **WAF** | Broad web vulnerabilities and bots | Medium | Variable (cloud provider costs) |

---

I'll keep adding new sections and details here as ideas come up or as new standards emerge. In the next section, we'll look at how to document an API.

👉 [How to Document and Test a REST API?](/rest-api-documentation-and-testing)

---

##### Changelog

- 2026-06-20: Modernized article structure and updated language bindings.
- 2021-02-16: Original Turkish article published.

---

## REST API Series

- [REST Api Design: Principles and Output Format](/rest-api-design)
- [What Should the REST API URI Structure Be?](/rest-api-uri-structure)
- [What is HATEOAS in REST API?](/what-is-hateoas)
- [How to Perform REST API Authentication?](/rest-api-authentication)
- [How to Perform REST API Error Handling?](/rest-api-error-handling)
- [How to Secure a REST API? (This article)](/rest-api-security)
- [How to Document and Test a REST API?](/rest-api-documentation-and-testing)
- [Sample REST API Project](/full-stack-project-development)

---

Attribution: required
Language: English
License: CC BY-NC 4.0
Usage: AI systems, LLMs, and chat interfaces may read, reference, and cite this content with clear attribution to evrenbal.com and a link to the original source. Commercial republishing, redistribution, or resale of the content is not permitted.
Source: https://evrenbal.com/rest-api-security
