Websites that fly. Leads that land.

API Integrations

How to Validate Third-Party API Data Before Saving It

Web applications increasingly depend on data from outside: product feeds from suppliers, orders from marketplaces, payments from gateways, leads from ad platforms, shipment updates from couriers and records from ERPs. It is tempting to trust that data and save it straight into your database. That is risky. Third-party API data can be incomplete, malformed, duplicated, outdated or simply different from what the documentation promised. Saving it without checks corrupts your records, breaks downstream processes and can even create security problems. This guide explains how to validate third-party API data before saving it.

Why Validation Matters

Real examples of bad external data include:

  • Prices sent as text with currency symbols or commas
  • Missing required fields, such as SKU or customer email
  • Dates in different formats or time zones
  • Status values that do not exist in your system
  • References to products or customers that are not in your database
  • Duplicate events sent several times
  • Fields that change type after an API update
  • Malicious content inserted into text fields

Each can cause errors that are expensive to discover later, especially when data flows on to accounting, fulfilment or customer communications.

Layer 1: Structural Validation

Check that the response has the expected shape:

  • Required fields are present
  • Data types are correct: numbers, strings, booleans, arrays
  • Nested objects contain expected keys
  • Lists are not unexpectedly empty

Use schema validation libraries, such as JSON Schema validators or typed data classes in your framework. Define schemas explicitly rather than assuming the API documentation is accurate.

Layer 2: Format and Range Validation

Check that values make sense:

FieldValidation rule
EmailValid format, normalised to lowercase
PhoneValid format, normalised with country code
PricePositive number, reasonable range, correct decimal places
QuantityInteger, not negative, within limits
DateValid date, correct time zone, not unreasonably far in past or future
CurrencyAllowed ISO code
Postal codeValid for the country

Normalise values to your internal formats before saving, for example converting all timestamps to UTC.

Layer 3: Business Rule Validation

Data can be valid in format but wrong for your business:

  • An order total that does not match the sum of its lines
  • A discount above the maximum allowed
  • A status change that skips required steps, such as shipped before paid
  • Stock values that drop by an implausible amount
  • A price change of more than a set percentage

Business rules catch errors that technical checks miss. Define them with the people who own each process.

Layer 4: Reference and Relationship Validation

Check that references point to existing records:

  • Products in an order exist in your catalogue
  • Customer IDs map to known customers
  • Warehouse codes are valid
  • Parent records exist before child records are saved

Decide what to do when references are missing: create placeholders, reject the record or hold it until the reference arrives.

Layer 5: Duplicate and Idempotency Checks

External systems often resend data. Use unique event IDs or natural keys, such as order number plus source, to detect duplicates. Make saving idempotent so the same record processed twice does not create two entries.

Layer 6: Security Validation

Treat all external data as untrusted:

  • Escape or sanitise text before displaying it, to prevent cross-site scripting
  • Use parameterised database queries
  • Validate file types and sizes for attachments
  • Verify webhook signatures and API authenticity
  • Limit payload sizes

Our website security practices cover these protections.

What to Do With Invalid Third-Party API Data

Never silently drop invalid data. Instead:

  1. Save the raw payload in a quarantine or staging table.
  2. Record the validation errors.
  3. Alert the responsible team for important data.
  4. Provide an admin screen to review, correct and reprocess records.
  5. Track error rates by source to identify systemic problems.

This approach protects your main database while preserving information for investigation.

Staging Tables and Transformation

For complex integrations, write incoming data to staging tables first, validate and transform it there, then move clean records into production tables. Staging separates “received” from “accepted”, making troubleshooting and reprocessing easier. This is a common pattern in our API integration development work.

Monitoring and Alerting

Track:

  • Records received, accepted, quarantined and rejected per source
  • Most common validation errors
  • Sudden changes in error rates, which often signal API changes on the provider side

Dashboards and alerts make data quality visible before it affects customers. Feeding these metrics into a website analytics dashboard keeps them in front of the right people.

Example: Supplier Feed Validation

A home improvement retailer imported product updates from 40 supplier APIs. One supplier changed its price field from a number to a formatted string, and thousands of products briefly showed prices of zero. After a redesign, every feed passed schema validation, price range checks and a rule rejecting changes above 30 percent without review. When another supplier changed its format months later, the records were quarantined, an alert was sent and the live site was unaffected.

Common Mistakes

  • Trusting API documentation without validating real responses
  • Silently ignoring invalid records
  • Validating format but not business rules
  • No idempotency for repeated events
  • Displaying external text without sanitising it

Where to Place Validation in Your Architecture

Validation works best as a clear, separate step rather than scattered checks across the codebase. A common pattern is: receive, store raw, validate, transform, save, then publish events to other parts of the application. Each step has a single responsibility and its own logs. Shared validation rules, such as allowed status values or price ranges, should live in one place so every integration applies them consistently. For applications receiving data from many sources, a small internal “integration hub” module that owns all of this logic makes maintenance far easier. Teams building on Laravel website development or Node.js web development stacks can use mature validation libraries to express these rules clearly and test them automatically.

Frequently Asked Questions

Doesn’t Validation Slow Down Integrations?

Slightly, but the cost is tiny compared with fixing corrupted data later.

Should We Reject or Fix Invalid Data Automatically?

Fix safe, predictable issues automatically, such as trimming spaces. Quarantine anything uncertain for review.

How Do We Know When an API Changes?

Monitor validation error rates and subscribe to provider change logs. Sudden error spikes often indicate a change.

Validating external data protects your systems and the decisions built on them. Explore our website integration services, review website backend development, learn about website testing and QA, see our integrations page, check ecommerce website development, or contact us.

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep reading

Free consultation

Want this done for your website?

Get a free consultation and a fixed quote.

    What do you need?
    Budget and timeline

    Where should we send your quote?

    No spam. Your details are only used to answer your request.

    Chat on WhatsApp