Think about how many applications you use every day. Online shopping, banking, food delivery, social media, and even your favorite productivity tools. Most of these applications communicate with backend systems through APIs. When you log in, update your profile, place an order, or make a payment, APIs help transfer information between different parts of the application. But there is something developers sometimes overlook: an API that works correctly is not necessarily a secure API.
Imagine building an eCommerce application where customers can view their orders through an API. If the backend does not properly check ownership, one customer might be able to access another customer's order simply by changing an order ID in the request.
That is a security problem, even if the API works exactly as programmed.
API security is about protecting data, controlling access, preventing unauthorized operations, and ensuring that applications behave safely.
In this guide, we'll explore 15 practical REST API security best practices, explain common vulnerabilities, and look at code examples that developers can apply to real-world applications.
What Is REST API Security?
REST API security refers to the techniques, rules, and mechanisms used to protect RESTful APIs from unauthorized access, data exposure, manipulation, and other security threats.
A secure API should ensure that:
Only authorized users can access protected resources.
Users can access only the data they are permitted to see.
Sensitive information is protected during transmission.
Incoming requests are properly validated.
Authentication credentials are handled securely.
Suspicious activity can be detected and investigated.
API operations cannot be easily abused.
Think of an API as a reception desk in an office building.
A visitor may enter the building, but that doesn't mean they should have access to every department, employee record, or confidential document.
Similarly, successfully authenticating a user does not automatically grant permission to access every API resource.
Why Is API Security Important?
APIs frequently handle sensitive information and business-critical operations.
For example, an eCommerce API may process:
Customer profiles.
Shipping and billing addresses.
Order history.
Payment transactions.
Loyalty points.
Discount coupons.
Product inventory.
If an API is not properly protected, attackers may exploit weaknesses to access data, manipulate transactions, or disrupt services.
Some common consequences of poor API security include:
Unauthorized access to customer information.
Account takeover.
Exposure of confidential business data.
Manipulation of orders or transactions.
Abuse of application functionality.
Financial losses.
Damage to customer trust and business reputation.
API security should therefore be considered from the beginning of application development, not added as an afterthought.
15 REST API Security Best Practices
1. Always Use HTTPS
HTTPS should be the starting point for every production API.
When an application communicates with an API over plain HTTP, information may be exposed to attackers who can intercept network traffic.
HTTPS uses TLS encryption to protect communication between the client and server.
For example:
Avoid:
http://api.example.com/usersUse:
https://api.example.com/usersHTTPS helps protect:
Authentication tokens.
User credentials.
Personal information.
API request and response data.
Sensitive business information.
Best practices:
Use valid TLS certificates.
Redirect HTTP traffic to HTTPS where appropriate.
Disable outdated TLS protocols and weak cipher suites.
Enable HSTS for websites where appropriate.
Avoid transmitting sensitive information in URL query parameters.
Remember that HTTPS protects data in transit. It does not replace authentication, authorization, or application-level security.
2. Implement Strong Authentication
Authentication verifies the identity of the person or system making an API request.
For example, when a customer logs into an application, the backend verifies their credentials before granting access.
Common API authentication mechanisms include:
Session-based authentication.
OAuth 2.0.
OpenID Connect.
API keys for suitable machine-to-machine use cases.
Signed tokens such as JWTs.
The correct mechanism depends on the application and its security requirements.
For applications using OAuth 2.0 or OpenID Connect, follow the recommended authorization flows rather than implementing a custom token system.
Best practices:
Never store passwords in plain text.
Use secure password hashing algorithms such as Argon2id or bcrypt.
Apply multi-factor authentication where appropriate.
Use short-lived access tokens where practical.
Implement secure refresh-token rotation and revocation.
Validate token signatures, expiration, issuer, and audience.
Never trust a token simply because it contains a valid-looking user ID.
For browser-based applications, carefully evaluate where tokens are stored and how they are protected against cross-site scripting and cross-site request forgery.
3. Implement Proper Authorization and Access Control
Authentication answers one question:
"Who are you?"
Authorization answers another:
"What are you allowed to do?"
This distinction is extremely important.
Imagine a shopping application with two customers:
Customer A has order ID 1001.
Customer B has order ID 1002.
If Customer A changes the API request from:
GET /api/orders/1001to:
GET /api/orders/1002the backend must verify that Customer A is allowed to access order 1002.
Simply checking whether the user is logged in is not enough.
This type of vulnerability is commonly associated with Broken Object Level Authorization (BOLA).
Best practices:
Verify resource ownership on the server.
Apply role-based access control where appropriate.
Implement permission checks for sensitive operations.
Use object-level authorization for individual records.
Do not rely on frontend restrictions.
Test access using different user accounts.
A secure API should enforce authorization on every relevant request, not just during login.
4. Validate and Sanitize All Input Data
Never assume incoming API data is trustworthy.
Requests may come from browsers, mobile applications, third-party services, scripts, or potentially malicious clients.
An attacker may deliberately send unexpected values to exploit weaknesses in your application.
For example:
{
"name": "<script>alert('test')</script>",
"age": "invalid",
"email": "not-an-email"
}Your API should validate the request before processing it.
Best practices:
Validate required fields.
Check data types and formats.
Apply maximum and minimum length restrictions.
Validate numeric ranges.
Restrict accepted enum values.
Validate uploaded files.
Reject unexpected fields where appropriate.
Use parameterized database queries.
Input validation should be based on the expected data structure rather than attempting to remove every potentially dangerous character.
For database operations, always use parameterized queries or a properly configured ORM.
For output displayed in browsers, apply context-appropriate output encoding to prevent cross-site scripting.
5. Protect Against SQL Injection
SQL injection occurs when untrusted input is incorporated into database queries in an unsafe way.
Consider the following vulnerable PHP example:
$email = $_GET['email'];
$sql = "SELECT * FROM users WHERE email = '$email'";An attacker may manipulate the input to change the meaning of the database query.
The problem is not the user input itself. The problem is constructing SQL by concatenating untrusted values.
A safer approach is to use prepared statements:
$stmt = $pdo->prepare(
"SELECT * FROM users WHERE email = :email"
);
$stmt->execute([
'email' => $email
]);Best practices:
Use prepared statements.
Avoid dynamic SQL concatenation.
Apply database least-privilege permissions.
Validate expected input types.
Avoid exposing database errors to API consumers.
Review database access patterns during security testing.
Using an ORM does not automatically make every query safe. Be especially careful with raw SQL and dynamically constructed queries.
6. Implement Rate Limiting
Not every API request is necessarily legitimate.
An attacker may send thousands of requests to an endpoint in a short period, attempting to overload the application or abuse its functionality.
This is where rate limiting becomes important.
Rate limiting controls how frequently a client can access an API.
For example:
API Endpoint | Example Limit |
|---|---|
Login | 5 attempts per minute |
Password reset | 3 attempts per 15 minutes |
Public search | 60 requests per minute |
General API | 100 requests per minute |
These are illustrative limits, not universal recommendations. Actual limits should be based on application behavior, user experience, and risk.
When a client exceeds the configured limit, the API can return:
HTTP/1.1 429 Too Many Requests
Retry-After: 60Best practices:
Apply stricter limits to login and password reset endpoints.
Consider user, account, IP, and API-key-based limits.
Use distributed rate limiting for applications running across multiple servers.
Return appropriate 429 responses.
Monitor unusual request patterns.
Avoid relying exclusively on IP-based limits.
Rate limiting helps reduce automated abuse, but it is not a complete defense against distributed denial-of-service attacks.
7. Protect Against Broken Object Property Level Authorization
A common API security problem occurs when applications expose or allow modification of properties that users should not control.
Imagine a customer updating their profile:
{
"name": "John Smith",
"email": "john@example.com"
}However, the backend also accepts unexpected fields:
{
"name": "John Smith",
"email": "john@example.com",
"role": "admin",
"is_verified": true
}If the application blindly updates every submitted property, a customer may be able to change privileged account attributes.
This is associated with Broken Object Property Level Authorization and mass-assignment vulnerabilities.
Best practices:
Explicitly allow permitted request fields.
Use dedicated input DTOs or request validation objects.
Never bind arbitrary request data directly to sensitive models.
Protect administrative properties.
Apply authorization to sensitive fields.
Return only the properties required by the client.
A good rule is to accept only the fields that a particular operation is designed to modify.
8. Secure API Keys and Access Tokens
API keys and access tokens are credentials. Anyone who obtains them may be able to access the associated services or resources.
Never expose private credentials in public source code.
For example, avoid hardcoding credentials in frontend JavaScript:
const API_KEY = "your-private-api-key";Anything delivered to a browser should be considered accessible to the user.
Best practices:
Store secrets in environment variables or a dedicated secrets manager.
Never commit credentials to source control.
Rotate compromised or expired credentials.
Apply appropriate expiration and revocation policies.
Restrict API keys to required services and permissions.
Monitor unusual credential usage.
Avoid logging access tokens.
Also remember that environment variables are not automatically secure if they are exposed through debug endpoints, logs, or misconfigured deployment environments.
9. Configure CORS Correctly
Cross-Origin Resource Sharing (CORS) controls which browser origins are permitted to access resources on another origin.
For example, imagine your frontend runs at:
https://www.example.comAnd your API runs at:
https://api.example.comThe browser may enforce CORS rules when the frontend calls the API.
A common mistake is allowing every origin without understanding the implications.
For example:
Access-Control-Allow-Origin: *This is not automatically insecure for every API, but it is inappropriate for many private APIs, particularly when credentials are involved.
Best practices:
Allow only trusted origins where possible.
Restrict allowed HTTP methods.
Restrict allowed request headers.
Avoid unnecessary wildcard configurations.
Do not combine credentialed browser requests with wildcard origins.
Validate CORS behavior in the browser.
Most importantly, CORS is a browser security mechanism, not an authentication or authorization system. Non-browser clients can call APIs regardless of browser CORS restrictions.
10. Protect Against Cross-Site Request Forgery (CSRF)
CSRF occurs when an attacker tricks an authenticated user's browser into sending an unwanted request to an application.
This is particularly relevant when applications use automatically attached browser cookies for authentication.
For example, a user may already be logged into a website. An attacker could attempt to trigger an unwanted account-changing action through a malicious webpage.
Best practices:
Use anti-CSRF tokens for cookie-authenticated state-changing requests.
Configure appropriate SameSite cookie attributes.
Validate request origins where appropriate.
Avoid using GET requests for operations that change application state.
Use secure cookie settings.
Consider the complete browser authentication model when designing protection.
Bearer-token APIs that require an authorization header and do not rely on automatically attached authentication cookies have a different CSRF risk profile. They still need appropriate protection against other attacks, especially XSS and token theft.
11. Prevent Excessive Data Exposure
APIs sometimes return more information than the frontend actually needs.
For example, a customer profile endpoint might return:
{
"id": 101,
"name": "John Smith",
"email": "john@example.com",
"password_hash": "...",
"internal_notes": "VIP customer",
"account_status": "active"
}The frontend may only need the customer's name and email.
Returning unnecessary fields increases the risk of exposing sensitive information.
Best practices:
Define explicit response schemas.
Return only necessary fields.
Avoid exposing internal database models directly.
Remove passwords, tokens, and internal attributes.
Apply property-level access control.
Review API responses during security testing.
Remember that hiding a field in the frontend does not protect it if the API still sends it.
12. Secure File Upload Endpoints
File uploads are another area that requires careful security controls.
Imagine an API that allows users to upload profile pictures or product images.
An attacker may attempt to upload an executable file disguised as an image.
For example:
profile-image.php.jpgChecking only the filename extension is not sufficient.
Best practices:
Allow only required file types.
Validate actual file content and MIME types.
Apply file size restrictions.
Generate unique filenames.
Store uploads outside executable web directories.
Prevent uploaded files from being executed.
Scan files where appropriate.
Apply access controls to private uploaded files.
Consider image re-encoding for supported image formats.
File upload security should be implemented on the server, regardless of frontend restrictions.
13. Disable Unnecessary HTTP Methods and API Endpoints
Every publicly accessible endpoint increases the application's attack surface.
If an API does not need certain HTTP methods, do not leave them enabled unnecessarily.
For example, a product endpoint may support:
GET /api/products
GET /api/products/100But it may not need to expose:
DELETE /api/products/100to ordinary customers.
Best practices:
Expose only required endpoints.
Restrict unsupported HTTP methods.
Apply authorization to administrative endpoints.
Remove deprecated API routes.
Avoid exposing development and debugging endpoints.
Review API routes regularly.
A smaller and well-controlled API surface is easier to maintain and secure.
14. Implement Security Logging and Monitoring
Even with strong security controls, applications should be prepared to detect suspicious activity.
For example, imagine a customer account receives hundreds of failed login attempts within a short period.
Without monitoring, the activity might go unnoticed.
Useful security events include:
Repeated failed login attempts.
Authentication failures.
Authorization failures.
Unusual API request patterns.
Rate-limit violations.
Unexpected administrative actions.
Suspicious access to sensitive resources.
Best practices:
Use structured application logs.
Include request and correlation IDs.
Monitor unusual authentication activity.
Alert on suspicious behavior.
Protect log access.
Define log retention policies.
Avoid storing passwords, access tokens, and unnecessary personal information.
Monitoring should help identify suspicious activity without creating another source of sensitive data exposure.
15. Perform Regular API Security Testing
Security is not a one-time implementation task.
New endpoints, dependencies, integrations, and business requirements can introduce vulnerabilities over time.
Regular testing helps identify weaknesses before they become serious incidents.
Consider including:
Static Application Security Testing (SAST)
Analyzes source code to identify potentially insecure coding patterns.
Dynamic Application Security Testing (DAST)
Tests running applications for security weaknesses.
Dependency Scanning
Identifies vulnerable third-party libraries and packages.
API Security Testing
Checks authentication, authorization, validation, rate limiting, and other API-specific controls.
Penetration Testing
A controlled security assessment designed to identify exploitable vulnerabilities.
Useful tools include:
OWASP ZAP.
Burp Suite.
Postman.
Snyk.
Semgrep.
Always perform security testing against systems you own or are explicitly authorized to assess.
Common API Security Threats Developers Should Know
The OWASP API Security Top 10 is a useful resource for understanding common API security risks.
Some important threats include:
Security Risk | What It Means |
|---|---|
Broken Object Level Authorization | Users access resources they should not be allowed to access |
Broken Authentication | Authentication mechanisms can be bypassed or abused |
Broken Object Property Level Authorization | Sensitive object properties are exposed or modified without proper permission |
Unrestricted Resource Consumption | APIs can be abused to consume excessive resources |
Broken Function Level Authorization | Users access functions outside their permissions |
Unrestricted Access to Sensitive Business Flows | Automated abuse of legitimate business operations |
Server Side Request Forgery | The server is tricked into making unintended requests |
Security Misconfiguration | Unsafe application or infrastructure settings |
Improper Inventory Management | Outdated or undocumented APIs remain exposed |
Unsafe Consumption of APIs | Third-party API responses are trusted without sufficient validation |
Understanding these risks helps developers move beyond basic authentication and consider the complete security of their API architecture.
Practical REST API Security Checklist
Before deploying an API to production, review the following checklist.
Authentication and Authorization
Use a secure authentication mechanism.
Validate tokens correctly.
Implement resource-level authorization.
Apply role-based permissions where appropriate.
Protect sensitive administrative operations.
Data Protection
Enforce HTTPS.
Never store passwords in plain text.
Protect access tokens and API keys.
Avoid exposing sensitive response properties.
Use secure file upload handling.
Request Validation
Validate all incoming request data.
Use parameterized database queries.
Restrict accepted request fields.
Apply appropriate input size limits.
Validate third-party API responses.
Infrastructure and Monitoring
Configure rate limiting.
Restrict CORS to trusted browser origins where applicable.
Disable unnecessary endpoints.
Maintain secure application configurations.
Monitor suspicious activity.
Scan dependencies regularly.
Perform security testing before major releases.
Frequently Asked Questions (FAQs)
1. What is REST API security?
REST API security refers to protecting RESTful APIs against unauthorized access, data exposure, injection attacks, and other security vulnerabilities through authentication, authorization, encryption, validation, and monitoring.
2. What is the most important API security practice?
There is no single control that makes an API secure. However, strong authentication combined with proper object-level and function-level authorization is fundamental. HTTPS, validation, rate limiting, and monitoring are also essential.
3. What is the difference between authentication and authorization?
Authentication verifies the identity of a user or system. Authorization determines what that authenticated identity is allowed to access or perform.
4. Is HTTPS enough to secure an API?
No. HTTPS protects data during transmission, but it does not prevent unauthorized access, SQL injection, broken authorization, or application logic vulnerabilities.
5. What is an API key?
An API key is a credential used to identify or authorize an application or integration when accessing an API. API keys should be protected, scoped appropriately, and rotated when necessary. They should not automatically be treated as proof of an individual user's identity.
6. What is JWT authentication?
JSON Web Token (JWT) is a compact token format that can carry signed claims between systems. It is commonly used in authentication and authorization architectures. Its security depends on correct signing, verification, expiration, audience validation, and secure token handling.
7. What is OWASP API Security Top 10?
It is an OWASP awareness resource that identifies major API security risks and provides guidance to help developers understand and prevent common vulnerabilities.
8. How often should API security be tested?
Security should be considered throughout development. Perform automated checks continuously where practical, test security-sensitive changes before release, and conduct periodic deeper assessments based on the application's risk.
Final Thoughts
Building a REST API is relatively straightforward. Building one that protects customer information, handles sensitive operations, and remains secure as the application grows requires more careful planning.
The good news is that many API vulnerabilities can be reduced by following established security practices.
Start with HTTPS, strong authentication, proper authorization, input validation, and secure database access. Then strengthen your application with rate limiting, monitoring, dependency scanning, and regular security testing.
Most importantly, never assume that a request is safe simply because it comes from your own frontend application.
Every API request should be treated as untrusted until the server has properly validated and authorized it.
A secure API protects more than application data. It protects users, businesses, and the trust people place in the software they use.
Keep building secure and reliable applications with AgileLogics.
Written by
James Okafor
DevOps engineer covering containers, CI/CD, and infrastructure workflows.