Skip to main content
RESTful Principles
CHAPTER 24 Beginner

REST API Security Best Practices

Updated: May 13, 2026
5 min read

# CHAPTER 24

REST API Security Best Practices

1. Introduction

If you build a beautiful, fast API but leave the doors unlocked, hackers will exploit it in minutes. Security is not an afterthought; it must be baked into every layer of your API. In Chapter 24, we will cover the critical security best practices every API developer must know. We will discuss HTTPS, defend against SQL Injection and XSS, and demystify the dreaded CORS (Cross-Origin Resource Sharing) errors.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain why HTTPS/TLS is non-negotiable for REST APIs.
  • Prevent SQL Injection using PDO.
  • Understand and configure CORS headers correctly.
  • Prevent Cross-Site Scripting (XSS) by encoding output.
  • Hide sensitive server information in HTTP headers.

3. Beginner-Friendly Explanation

Imagine your API is a fortress.
  • HTTPS: The armored truck that securely transports data to and from the fortress. Without it, anyone on the street can read your mail.
  • SQL Injection Prevention: Checking everyone's pockets at the gate to ensure they aren't carrying a bomb designed to blow up your database.
  • CORS: The guest list. Telling the browser exactly which other websites are allowed to talk to your fortress via JavaScript.
  • XSS Prevention: Ensuring that if a user writes graffiti on the fortress walls, it is treated as harmless paint, not as instructions for the guards to follow.

4. Real-World Examples

  • CORS Error: You build a React app on http://localhost:3000 and try to fetch data from your PHP API on http://localhost:8000. The browser blocks it with a red error in the console. This is CORS protecting the user!
  • Data Breach: A company fails to use HTTPS. A user logs in at a public coffee shop. A hacker on the same Wi-Fi intercepts the HTTP packet in plain text and steals the API token.

5. Detailed Code Examples

Let's look at how to properly configure CORS in PHP and how to hide PHP version information.

1. Secure Headers (index.php):

php
12345678910111213141516171819
<?php
// 1. CORS Configuration
// Allow requests from your specific frontend app (Do NOT use '*' in production!)
header("Access-Control-Allow-Origin: https://myfrontendapp.com");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// 2. Security Headers
header("X-Content-Type-Options: nosniff"); // Prevents MIME-sniffing
header("X-Frame-Options: DENY"); // Prevents clickjacking

// 3. Handle OPTIONS request for CORS Preflight
if ($_SERVER[&#039;REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

// ... rest of API logic ...
?>

2. Hiding PHP Version (php.ini): By default, PHP sends a header like X-Powered-By: PHP/8.1.2. Hackers use this to find known vulnerabilities in that specific PHP version. Turn it off in your php.ini file:

ini
1
expose_php = Off

6. Request/Response Examples

A securely configured API response will include several security headers.

Response:

http
1234567
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Access-Control-Allow-Origin: https://myfrontendapp.com
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000; includeSubDomains

{"data": "Secure information"}

7. HTTP Examples

HTTPS vs HTTP: Never accept http:// requests for an API. At the server level (Apache/Nginx), configure a redirect so that any traffic hitting port 80 (HTTP) is instantly redirected to port 443 (HTTPS). Without HTTPS, API keys and JWTs are sent in plain text across the internet.

8. JSON Examples

To prevent XSS (Cross-Site Scripting), ensure that if a user submits malicious HTML in a JSON payload, you encode it before returning it to the frontend.

Input Payload:

json
1
{"comment": "<script>alert(&#039;Hacked!');</script>"}

Output Payload (Sanitized via htmlspecialchars in PHP):

json
1
{"comment": "<script>alert(&#039;Hacked!');</script>"}

*Now, when the frontend displays the comment, it shows as raw text instead of executing the dangerous script.*

9. Best Practices

  • Never trust user input: Always use PDO Prepared Statements. We covered this in Chapter 21, but it is the single most important security rule in backend development.
  • Principle of Least Privilege: Ensure the MySQL user your API connects with only has permissions to SELECT, INSERT, UPDATE, DELETE. It should not have DROP TABLE or GRANT permissions.
  • Rate Limiting: Protect your endpoints from Brute Force and DDoS attacks by limiting how many requests a single IP can make per minute. (We cover this in the next chapter).

10. Common Mistakes

  • Access-Control-Allow-Origin: * in Production: While * is fine for public, read-only APIs (like a weather API), it is highly dangerous for authenticated APIs. If you use *, ANY website on the internet can make JavaScript requests to your API. Always lock it down to your specific frontend URL.
  • Storing Passwords in Plain Text: Never store raw passwords. Always use PHP's passwordhash() and passwordverify() functions.

11. Mini Exercises

  1. 1. Open a website, press F12, go to the Network tab, and click a request. Look at the Response Headers. Can you find the Access-Control-Allow-Origin or X-Powered-By headers?

12. Coding Challenges

Challenge 1: Write a PHP snippet that takes an array $data = ["name" => "<script>bad</script>"], sanitizes the name value using htmlspecialchars(), and then jsonencodes it.

13. MCQs with Answers

Question 1

What is the primary purpose of HTTPS?

Question 2

Which HTTP header is used to resolve CORS errors in the browser?

Question 3

How do you prevent SQL Injection in a PHP API?

14. Interview Questions

  • Q: Explain what CORS is, why browsers enforce it, and how to configure an API to bypass it safely.
  • Q: Why is it dangerous to leave exposephp = On in your server configuration?
  • Q: If an API requires a Bearer token, why is using HTTPS absolutely mandatory?

15. FAQs

Q: Does CORS protect my API from hackers? A: No! This is a huge misconception. CORS is a *browser* security feature. It stops malicious websites from making background requests from a user's browser. However, a hacker using Postman or cURL ignores CORS entirely. CORS protects your users, not your server.

16. Summary

In Chapter 24, we locked down the fortress. We established that HTTPS is mandatory to protect tokens in transit. We configured strict CORS headers to allow our frontend apps to communicate with our API while blocking malicious websites. We also learned to sanitize JSON output to prevent XSS and hide our server's tech stack metadata from potential attackers.

17. Next Chapter Recommendation

Our API is secure from hackers, but what if a bot tries to spam our server with 10,000 requests per second to crash it? Proceed to Chapter 25: Rate Limiting and Throttling to learn how to defend against abuse.

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: ·