Go to content
Web development

Treat Third-Party API Responses as Untrusted Input

When your service gets data from a payment provider, shipping service, or another outside API, the provider’s familiar name does not guarantee that each response is complete, correctly formatted, or safe to store. The response comes from outside your service’s control. Treat it as untrusted until your code checks that it has the fields and values your service expects.

Check the response before your code maps it to an internal data structure or writes it to a database. A schema describes the expected structure and data types. Value bounds set acceptable limits, such as a maximum string length or an allowed number range. OWASP API10, “Unsafe Consumption of APIs,” describes the risk of trusting outside API data too readily, including harmful data injection and service disruption. Runtime checks help catch these problems even when you test the provider’s interface.

This article covers data that an outside service returns. Checking requests from your own clients is a separate task. Checking URLs that users supply to prevent server-side request forgery (SSRF) addresses a different risk.

Validate before creating internal records

Check the HTTP response before your code updates the database or internal data structures. Check the response status and limit how much data you accept. Then parse the body and verify its structure and values before mapping accepted fields to your own data types.

For example, a provider might return a payment with an identifier, an amount, and a currency. Your service should check that the body is an object with those fields. It should check that the identifier is a nonempty string within your length limit, the amount is a valid number within the range your payment logic supports, and the currency is one your service handles. A value can have the right data type and still be invalid for your business rules, so check more than types.

type ProviderPayment = {
  id: string;
  amount: number;
  currency: string;
};

function parseProviderPayment(value: unknown): ProviderPayment {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    throw new Error("Invalid payment response: expected an object");
  }

  const record = value as Record<string, unknown>;

  if (
    typeof record.id !== "string" ||
    record.id.length === 0 ||
    record.id.length > PAYMENT_ID_MAX_LENGTH
  ) {
    throw new Error("Invalid payment response: invalid id");
  }

  if (
    typeof record.amount !== "number" ||
    !Number.isFinite(record.amount) ||
    record.amount < PAYMENT_MIN_AMOUNT ||
    record.amount > PAYMENT_MAX_AMOUNT
  ) {
    throw new Error("Invalid payment response: invalid amount");
  }

  if (
    typeof record.currency !== "string" ||
    !SUPPORTED_CURRENCIES.has(record.currency)
  ) {
    throw new Error("Invalid payment response: unsupported currency");
  }

  return {
    id: record.id,
    amount: record.amount,
    currency: record.currency,
  };
}

Set the constants and supported currencies from your provider contract and business rules. The limits are not universal; they depend on what your service accepts and stores. Give the parser a return type more specific than unknown. Then pass only its result to code that creates or updates internal records. This makes the validation check clear in the code.

Handle missing, malformed, and oversized responses

Do not let a response with a missing body, invalid JSON, or a missing required field reach storage. Treat each case as a failed result from the provider. Record enough detail to investigate it, then return an error or use a fallback the provider has documented. Do not silently replace a required value with an empty string, zero, or empty object. Those defaults can turn a provider failure you could detect into a misleading internal record.

Check the body size before parsing. The Content-Length header can help your code reject an obviously oversized response early, but the header alone is not enough. Enforce a byte limit as your code reads the body. Choose the limit based on the provider’s documented response size and your service’s needs. Then test what your code does when the body exceeds the limit. This keeps your code from parsing a response larger than it can handle.

Retry only when the failure is likely to be temporary, such as a network interruption or a provider status that allows retries. Repeating the request will not fix invalid JSON or a response that keeps breaking your expected structure. Handle malformed responses separately from temporary network failures so your code does not keep retrying unusable data.

Treat schema drift as a compatibility decision

Schema drift happens when an outside service changes its response from what your code expects. The provider might add or rename a field, change a value’s type, or omit a field your service needs. Your parser should accept a change only if your service can still use the data.

An added field does not have to break your integration if your service ignores it and still checks every field it uses. If the provider renames a required field or changes the amount’s type, validation should fail until you decide how to support the new contract. Do not pass the entire provider response into internal storage just because some fields look familiar. Map only the fields your service needs.

Contract tests can catch known compatibility changes before you deploy. In a consumer-driven contract test, the service that uses the API records the response fields it relies on. The provider then checks whether it still meets those expectations. Pact’s workflow shows how to check selected response fields without requiring the entire JSON body to stay identical. Contract tests cover the interactions you declare. They do not prove that every live response is valid or provide complete security. Keep checking responses while your service runs.

Test the failures your parser must reject

Test the validation checks with more than a successful provider response. Test a missing body, invalid JSON, a missing required field, the wrong type, a value outside your business limits, an oversized body, and a changed response structure. For each case, check that your code rejects the response and does not create or update a stored record.

Use fixed response bodies in these tests instead of relying on a live provider. Then you can reproduce malformed responses and schema changes even if the provider is unavailable or has not changed its API yet. Contract tests separately check whether the provider still matches the interactions your service declared. The two kinds of tests answer different questions.

More in Web development Back to top ↑