• Browse topics
Login

Unsafe consumption of APIs

Don't always trust external data sources

Select your ecosystem

Unsafe consumption of APIs: the basics

What is unsafe consumption of APIs?

Unsafe consumption of APIs occurs when developers trust data from external or third-party APIs without proper validation, sanitization, or security checks. This vulnerability arises from assuming that data provided by other APIs is inherently safe. However, attackers can exploit weaknesses in these integrations to manipulate or inject malicious data into the system, leading to outcomes such as sensitive data exposure, denial of service, or injection attacks.

About this lesson

In this lesson, you will learn how unsafe consumption of APIs can expose your application to significant risks. You will explore common scenarios where this vulnerability occurs, examine how attackers exploit it, and discover best practices to secure your integrations with third-party APIs.

Unsafe consumption of APIs in action

Laura is a developer at a real estate company. Her team integrates their platform with a third-party API that enriches property data by fetching additional details like nearby schools and demographic statistics. This API simplifies the company’s work but comes with hidden risks!

Things are off to a rough start with the API

Looking at the image above, clearly things aren't going well with the API that has been integrated. A popup with the word Hacked! is generally not a good thing. But why is this happening?

Laura and her team took a look at what is actually being fetched by the API. They viewed the data being fetched from the third-party API in the network tab of their browser's dev tools. The fetched data included some standard property stats ( bedrooms, bathrooms, car parking spots, etc.) but also something else.

{
 "propertyId": "12345",
 "businessName": "<script>alert('Hacked!');</script>",
 "address": {
   "street": "456 Security Lane",
   "city": "Boston",
   "state": "Massachusetts",
   "postcode": "02108",
   "country": "USA"
 },
 "stats": {
   "bedrooms": 4,
   "bathrooms": 2,
   "carParkingSpots": 2
 },
 "amenitiesNearby": [
   {
      "type": "School",
      "name": "Local Primary School",
      "distance": "1.2km"
   },
   {
      "type": "Shopping Center",
      "name": "Sunshine Plaza",
      "distance": "2.5km"
   }
 ],
 "ratings": {
   "walkScore": 74,
   "transitScore": 68
 }
}

In this scenario, the issue arises from blindly trusting data provided by a third-party API. Let’s break down how the vulnerability occurs step by step.

Unsafe consumption of APIs under the hood

Data flow and processing

Laura’s application makes an HTTP request to a third-party API to fetch property-related data. This API returns a JSON response containing details like the property address, nearby amenities, and the name of a local business. Laura trusts this data because she feels that this 3rd party API is reputable and trustworthy, however, one of the business names includes a malicious JavaScript payload: <script>alert("Hacked!")</script>.

The application processes this data and injects it directly into the DOM of the web page without proper validation or escaping. When the page renders, the browser interprets the JavaScript code in the malicious business name field, triggering the alert box. This is a classic cross-site scripting (XSS) vulnerability, but triggered by an unexpected source. Let’s examine how this vulnerability manifests in code.

Vulnerable code examples

This Python Flask application retrieves property details from a third-party API and embeds the businessName field into an HTML template. The businessName function renders the HTML and sends it to the browser.

What is the impact of unsafe consumption of APIs?

If you’re not careful about how your application handles API responses, you’re opening the door to a whole range of security issues. One of the biggest risks is cross-site scripting (XSS), where an API response contains a malicious script that runs in the user’s browser. This can expose session tokens, steal sensitive data, or redirect users to phishing sites—none of which are great for security or user trust.

Another common issue is accidentally exposing sensitive data. If your application doesn’t properly validate API responses, attackers can manipulate them to extract things like login credentials, financial records, or other private information.

Then there’s injection attacks. SQL injection, command injection, and similar exploits. If your app blindly trusts API data and feeds it directly into a database query or system command, an attacker could gain unauthorized access, compromise your system, or even take down the whole application. And let’s not forget denial-of-service (DoS) attacks! Poor handling of large or malformed API responses can overload system resources and crash your app.

Beyond the technical damage, these vulnerabilities can seriously hurt your business. A data breach or service disruption can damage your reputation, break customer trust, and even lead to legal trouble or financial penalties. That’s why it’s so important to validate, monitor, and securely handle API integrations.

Scan your code & stay secure with Snyk - for FREE!

Did you know you can use Snyk for free to verify that your code
doesn't include this or other vulnerabilities?

Scan your code

Unsafe consumption of APIs mitigation

Protecting your app from the risks of unsafe API consumption comes down to a few key strategies: validating data, securing communication, and keeping a close eye on API activity.

First, always validate and sanitize any data coming from third-party APIs before using or displaying it. That means checking data types, lengths, and formats to make sure nothing malicious slips through. Encoding potentially dangerous characters also helps prevent attacks like cross-site scripting (XSS) when integrating API data into a web app.

Next, secure the connection between your app and the API. Always use HTTPS, and make sure SSL certificates are properly validated to prevent man-in-the-middle attacks. Also, don’t blindly follow redirects from APIs—stick to a whitelist of trusted domains so attackers can’t send requests somewhere harmful.

To keep your app running smoothly, set up proper timeout settings and rate limiting. This helps prevent denial-of-service (DoS) attacks and protects against issues caused by unreliable or poorly designed APIs. Good error handling is just as important—assume that API responses might be incomplete, malformed, or just plain wrong, and make sure your app can handle those situations gracefully.

Finally, monitoring and logging API activity is a must. Keeping track of API requests and responses can help spot unusual patterns or potential security threats before they become major problems. Regularly reviewing third-party integrations and the APIs themselves can also help catch vulnerabilities before attackers do.

Together, these practices create a strong foundation for securely consuming APIs and protecting both the application and its users from harm.

Mitigated code

The vulnerable version directly embeds the businessName field into the HTML string without any processing, which allows malicious scripts in the data to execute. The remediated code uses the html.escape function to encode special characters in the businessName field, ensuring the output is safe for rendering.

The use of html.escape prevents any HTML or JavaScript within the businessName field from being interpreted as code. Instead, special characters like < and > are converted to their corresponding HTML entities (&lt; and &gt;), rendering the data harmless when displayed in the browser.

General mitigation patterns across languages

A common mistake that leads to vulnerabilities is blindly trusting data from third-party APIs. Just because the data comes from an API doesn’t mean it’s safe. Attackers can manipulate API responses just like they can with user input. That’s why you should always handle API data with the same level of caution as any other untrusted input.

Start by validating everything. Check data types, lengths, formats, and expected values before using or displaying API responses. If your application expects a number but gets a string (or worse, a script), it should reject or sanitize it.

Encoding is just as important. If API data is being inserted into a webpage, ensure it’s properly encoded to prevent cross-site scripting (XSS). The same applies to SQL queries—never directly insert API data into a query without sanitization to avoid injection attacks.

Additionally, implement proper error handling. APIs can fail, return unexpected responses, or even be hijacked. Your application should be able to detect and handle these situations without breaking or exposing security gaps.

By treating third-party API data as potentially malicious, validating it thoroughly, and encoding it where needed, you reduce the risk of security vulnerabilities and keep your application more secure.

Quiz

Test your knowledge!

Quiz

What is the biggest security risk of consuming third-party API data without validation?

Keep learning

To deepen your understanding of API security and related vulnerabilities, consider exploring the following resources:

Congratulations

You have taken your first step into learning about unsafe consumption of APIs, how they work, their potential impacts, and how to protect your applications from this vulnerability. By applying the knowledge from this lesson, you can make your applications more robust and secure against threats that might arise from untrusted third-party APIs.