Skip to content

Vibe Coding Third-Party Integrations Safely: APIs, Webhooks, and Error Handling

Connecting an API is easy. Building an integration that handles secrets, authentication, timeouts, retries, webhooks, and failures safely is harder. Learn a practical approach to integrating third-party services with AI coding agents.

vibe codingAI coding agentsAPI integration

Vibe Coding Third-Party Integrations Safely: APIs, Webhooks, and Error Handling

One of the most exciting parts of building an application with AI coding agents is connecting it to real services.

You can ask an agent to add email notifications, connect a payment provider, enable Google sign-in, upload files to cloud storage, or retrieve information from an external API. Within a short time, you may have a working integration.

But there is a difference between making an API request work once and building an integration that remains reliable in production.

What happens when the external service is unavailable? What if the API key accidentally appears in browser code? What if a webhook is delivered twice? What if a payment provider sends an event before your application has finished saving the related record?

These are not unusual situations. They are part of building software that depends on other systems.

In this guide, we'll look at how to plan, implement, test, and secure third-party integrations when working with AI coding agents. We'll cover API credentials, authentication, request validation, webhooks, retries, idempotency, monitoring, and practical prompts you can reuse in your own projects.

1. Understand what a third-party integration actually involves

A third-party integration connects your application to a service maintained outside your own system.

For example:

IntegrationWhat your application uses it for
Payment providerAccepting payments and receiving payment updates
Email providerSending transactional emails
Authentication providerSigning users in through an external identity service
Cloud storageUploading and retrieving files
Maps or geolocation APIDisplaying locations and calculating routes
Analytics serviceCollecting application usage information
Messaging serviceSending notifications and messages

Most integrations involve one or more of these communication patterns.

API requests

Your application sends a request to an external service and receives a response.

For example:

Your application
       |
       | HTTPS request
       v
External API
       |
       | JSON response
       v
Your application

Your application controls when it makes the request.

Webhooks

An external service sends an HTTP request to your application when an event occurs.

For example:

Payment provider
       |
       | Payment completed event
       v
Your webhook endpoint
       |
       | Verify and process event
       v
Your database

The external service controls when the event is delivered. Your application must be ready to receive it.

OAuth and delegated access

OAuth allows an application to obtain limited access to a user's resources without asking the user to share their account password with your application.

For example, a user might authorize your application to access selected information from another platform.

OAuth introduces additional responsibilities such as redirect validation, state checking, token handling, and permission scopes.

These patterns are related, but they are not interchangeable. Before asking an AI agent to implement an integration, identify which pattern the service actually requires.

2. Start with the provider's official documentation

Before writing code, find the official documentation for the service.

Do not rely entirely on a blog post, a generated example, or an old code snippet.

Look for these details:

  • Authentication method
  • API base URL
  • Supported endpoints
  • Required headers
  • Request and response formats
  • Rate limits
  • Error response formats
  • Timeout recommendations
  • Retry behavior
  • Webhook signature requirements
  • API versioning and deprecation policy
  • Test or sandbox environment

Create a short integration specification in your project.

For example:

# Email Provider Integration

## Purpose
Send transactional emails from the application.

## Authentication
Server-side API key.

## Required Operations
- Send verification email.
- Send password reset email.
- Send account notification.

## Configuration
EMAIL_API_KEY
EMAIL_API_BASE_URL
EMAIL_FROM_ADDRESS

## Reliability Requirements
- Apply request timeouts.
- Handle provider errors.
- Avoid logging credentials.
- Record delivery attempts.
- Do not retry permanent failures indefinitely.

## Security Requirements
- Keep API credentials server-side.
- Validate recipient addresses.
- Apply appropriate rate limits.
- Do not expose sensitive email content in logs.

This gives the coding agent a clear target.

Important: Use the provider's real documentation for exact endpoints, headers, authentication formats, and response schemas. The example above is an integration planning template, not a real provider configuration.

3. Design the integration before implementing it

A common mistake in vibe coding is asking an agent to connect a service without defining how the integration should fit into the application.

For example:

Connect my application to a payment API.

That instruction leaves several important questions unanswered.

  • Where will the API request run?
  • How will credentials be stored?
  • Which application feature needs the integration?
  • What happens if the provider fails?
  • How will payment status be updated?
  • What happens if an event arrives more than once?
  • How will the integration be tested?

Instead, define the integration boundary.

A useful architecture looks like this:

Frontend
   |
   | Application request
   v
Backend API
   |
   | Validation and authorization
   v
Integration service
   |
   | Authenticated HTTPS request
   v
Third-party provider
   |
   | Response or webhook event
   v
Backend processing
   |
   v
Database

The frontend should communicate with your backend for operations that require private credentials or privileged access.

The integration service should be responsible for provider-specific details, such as authentication headers, request formats, response mapping, and error handling.

This prevents provider-specific code from spreading across unrelated components.

Example project structure

For a typical TypeScript application:

src/
├── app/
│   └── api/
│       └── integrations/
│           └── email/
│               └── route.ts
├── integrations/
│   └── email/
│       ├── client.ts
│       ├── schemas.ts
│       ├── errors.ts
│       └── types.ts
├── lib/
│   ├── env.ts
│   └── logger.ts
└── services/
    └── notification.service.ts

This is one possible organization. Adapt it to your framework and existing architecture.

The important principle is separation of responsibilities:

  • Route handlers manage incoming application requests.
  • Integration clients communicate with external providers.
  • Schemas validate data.
  • Services implement application-level behavior.
  • Logging records useful operational information without exposing secrets.

4. Protect API keys and credentials

Credentials are one of the most important parts of an integration.

An API key may grant permission to send emails, access customer records, modify resources, or perform paid operations.

If a private key is exposed, someone else may use it without your permission.

Keep private credentials on the server

Never place private provider credentials directly in frontend code.

For example, this is unsafe:

const apiKey = "sk_live_example_secret";

fetch("https://api.example.com/data", {
  headers: {
    Authorization: `Bearer ${apiKey}`,
  },
});

Anything included in browser-delivered JavaScript can potentially be inspected by users.

Instead, read credentials from server-side environment configuration:

const apiKey = process.env.EMAIL_API_KEY;

if (!apiKey) {
  throw new Error("Email provider configuration is missing");
}

The exact environment access mechanism depends on your framework.

Some frameworks distinguish public and private environment variables using naming conventions. Check the framework documentation before exposing any variable to client-side code.

Use environment variables safely

A local .env.example file can document required configuration without containing real credentials.

EMAIL_API_KEY=replace_with_test_api_key
EMAIL_API_BASE_URL=https://api.example.com
EMAIL_FROM_ADDRESS=no-reply@example.com

Add the real local environment file to .gitignore where appropriate.

For production, use the hosting platform's secret-management feature or a dedicated secrets manager.

Do not commit real credentials, include them in screenshots, or paste them into an AI prompt unnecessarily.

If a credential is accidentally committed or exposed, deleting it from the latest version is not enough. Revoke or rotate it with the provider and investigate where it may have been accessed.

Useful references:

5. Choose the correct authentication method

Different providers use different authentication mechanisms.

The most common patterns include:

API keys

A provider gives your application a key that identifies or authorizes it.

API keys are common for server-to-server integrations, but they must be protected and restricted according to the provider's capabilities.

Do not assume that possessing an API key automatically makes every request safe. Your application still needs authentication, authorization, and appropriate access controls.

Bearer tokens

A bearer token is sent in an HTTP authorization header:

Authorization: Bearer YOUR_ACCESS_TOKEN

Anyone who obtains a valid bearer token may be able to use its permissions. Protect it like a password.

OAuth 2.0

OAuth is commonly used when an application needs delegated access to another service.

For example:

  1. Your application redirects the user to the provider.
  2. The user reviews and approves requested permissions.
  3. The provider redirects the user back to your application.
  4. Your backend validates the response and exchanges the authorization code.
  5. Your application stores tokens securely and uses them according to their scope and lifetime.

For authorization-code flows, use the provider's recommended security mechanisms, including state validation and PKCE where supported and appropriate.

Do not build an OAuth flow from a random snippet. Follow the provider's official implementation guidance.

Reference: OAuth 2.0 Security Best Current Practice — RFC 9700.

6. Build a reusable API client

Instead of writing a separate raw fetch() call in every feature, create a reusable integration client.

This gives you one place to manage:

  • Base URLs
  • Authentication headers
  • Request timeouts
  • Response handling
  • Error conversion
  • Provider-specific behavior

Here is a simple TypeScript example:

type ApiClientOptions = {
  baseUrl: string;
  apiKey: string;
  timeoutMs?: number;
};

class ExternalApiError extends Error {
  constructor(
    message: string,
    public readonly status?: number
  ) {
    super(message);
    this.name = "ExternalApiError";
  }
}

export function createApiClient(options: ApiClientOptions) {
  const { baseUrl, apiKey, timeoutMs = 10000 } = options;

  return {
    async get<T>(path: string): Promise<T> {
      const url = new URL(path, baseUrl);

      const response = await fetch(url, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${apiKey}`,
          Accept: "application/json",
        },
        signal: AbortSignal.timeout(timeoutMs),
      });

      if (!response.ok) {
        throw new ExternalApiError(
          "External API request failed",
          response.status
        );
      }

      return response.json() as Promise<T>;
    },
  };
}

Example usage:

const apiKey = process.env.EXTERNAL_API_KEY;
const baseUrl = process.env.EXTERNAL_API_BASE_URL;

if (!apiKey || !baseUrl) {
  throw new Error("External API configuration is missing");
}

const client = createApiClient({
  apiKey,
  baseUrl,
  timeoutMs: 10000,
});

This example is intentionally small. A production client should also consider:

  • Validating the base URL and allowed destination.
  • Validating request and response schemas.
  • Handling non-JSON responses where relevant.
  • Handling 204 No Content responses.
  • Mapping provider errors into safe application errors.
  • Supporting the provider's documented authentication and versioning requirements.
  • Applying appropriate retry policies.
  • Limiting response sizes where appropriate.

Also, avoid treating a TypeScript type assertion as runtime validation. The expression response.json() as Promise<T> does not prove that the external response actually matches T.

Use a runtime schema validator or explicit validation for untrusted provider responses.

7. Handle API errors without breaking the application

External services fail for many reasons.

A request may time out, the provider may be unavailable, credentials may expire, a rate limit may be reached, or the request may be invalid.

Your application should not assume that every external request succeeds.

Common HTTP status codes include:

StatusMeaningTypical response
200Successful requestProcess the response
201Resource createdStore or display the result
204Successful request without response bodyHandle an empty response
400Invalid requestReview the input or payload
401Missing or invalid authenticationCheck credentials or token
403Access is not permittedCheck permissions and scopes
404Resource not foundCheck the identifier
409ConflictResolve the state conflict
429Rate limit exceededFollow provider retry guidance
500Provider-side failureHandle temporary failure
503Service unavailableApply a suitable recovery strategy

The exact meaning and retry behavior must be checked in the provider's documentation.

Separate provider errors from application errors

Do not send raw provider responses directly to the browser.

A provider error might contain internal identifiers, diagnostic information, or data that should not be exposed.

Instead, translate it into a safe application response.

For example:

try {
  const result = await sendNotification();

  return {
    success: true,
    data: result,
  };
} catch (error) {
  logger.error("Notification delivery failed", {
    errorType:
      error instanceof Error
        ? error.name
        : "UnknownError",
  });

  return {
    success: false,
    message: "Unable to send the notification. Please try again.",
  };
}

The logger in this example is illustrative. In production, use structured logging and avoid recording tokens, passwords, full sensitive payloads, or unnecessary personal information.

The user should receive a useful message, while the server retains enough safe diagnostic information to investigate the failure.

8. Use timeouts, retries, and backoff carefully

Imagine your application sends an email request, but the provider takes too long to respond.

Should the application wait indefinitely?

No. External requests should have a defined timeout.

A timeout limits how long your application waits for a response. It does not necessarily mean the provider did not process the request.

This distinction matters for operations such as payments or resource creation.

For example, a payment request may reach the provider successfully, but your application may time out before receiving the response. Sending a new payment request blindly could create a duplicate operation.

Retry only when it is safe

A common mistake is retrying every failed request.

A better approach considers:

  • The HTTP method and operation semantics.
  • Whether the provider supports idempotency keys.
  • Whether the error is temporary or permanent.
  • The provider's retry guidance.
  • Whether the request may already have been processed.

Typical guidance:

SituationRetry approach
Network timeoutRetry only with suitable duplicate protection
Temporary server errorFollow provider guidance and use bounded retries
Rate limit responseRespect Retry-After where provided
Invalid requestFix the request; don't retry unchanged
Invalid credentialsCorrect credentials; don't retry repeatedly
Permission deniedFix permissions or scopes
Resource not foundVerify the identifier and expected state

Use exponential backoff

When retries are appropriate, exponential backoff increases the wait between attempts.

A simple formula is:

[ delay = \min(maxDelay,\ baseDelay \times 2^{attempt}) ]

In practice, add random jitter to reduce the chance that many clients retry at exactly the same time.

For example, a retry schedule might use approximately 1 second, 2 seconds, and 4 seconds before stopping, subject to provider limits and a total time budget.

Do not retry indefinitely. Define a maximum attempt count and an appropriate failure path.

9. Understand idempotency before integrating payments

Idempotency is one of the most important concepts in reliable integrations.

An operation is idempotent when repeating it with the same logical request does not create additional unintended effects.

Imagine a user clicks the payment button. Your application sends a payment request, but the network times out.

The application does not know whether the payment provider processed the request.

If the user clicks again and your application creates a new payment operation, the customer could be charged twice.

An idempotency key can help prevent this when the provider supports it.

Conceptually:

POST /payments
Authorization: Bearer YOUR_SECRET
Idempotency-Key: unique-operation-identifier
Content-Type: application/json

The key should identify one logical payment attempt and be reused when safely retrying that same operation. A new independent payment operation should receive a new key.

Do not generate a new key for every retry. Doing so can defeat the duplicate-protection mechanism.

Also, do not assume every provider implements idempotency in the same way. Check its documentation for supported methods, key lifetime, request matching, and behavior when the original request is still processing.

Important: Idempotency does not replace payment-state verification. Your application should still reconcile the final payment status with the provider.

10. Understand webhooks and why they need special protection

An API request is initiated by your application. A webhook is initiated by an external service.

For example, when a customer completes a payment, the provider may send an event to your webhook endpoint.

Your endpoint might receive an event such as:

{
  "id": "evt_example_123",
  "type": "payment.completed",
  "data": {
    "payment_id": "pay_example_456",
    "status": "completed"
  }
}

This is illustrative JSON, not a real provider payload.

Your application might use the event to update an order, activate a subscription, or send a confirmation email.

But your webhook endpoint is exposed to incoming requests. An attacker could send a fake request that looks like a legitimate event.

Never trust a webhook just because it contains familiar JSON fields.

Verify webhook signatures

Providers commonly sign webhook deliveries so your application can verify that the message came from the expected provider and has not been altered.

A typical verification flow is:

  1. Read the raw request body.
  2. Read the signature headers.
  3. Retrieve the correct signing secret from server-side configuration.
  4. Use the provider's official SDK or verification library.
  5. Reject invalid signatures.
  6. Apply freshness or replay protections supported by the provider's protocol.
  7. Only then process the event.

Do not implement a provider's signature algorithm from memory when an official verification library is available.

For providers that require the original raw request body, parsing and reserializing JSON before verification can invalidate the signature.

Example webhook endpoint structure

The following is framework-neutral pseudocode written in TypeScript style. Replace the verification method with the actual provider SDK.

async function handleWebhook(request: Request) {
  const rawBody = await request.text();

  const signature = request.headers.get(
    "provider-signature"
  );

  if (!signature) {
    return new Response("Missing signature", {
      status: 401,
    });
  }

  const secret = process.env.WEBHOOK_SIGNING_SECRET;

  if (!secret) {
    return new Response("Webhook unavailable", {
      status: 500,
    });
  }

  let event;

  try {
    event = verifyWithProviderSdk({
      rawBody,
      signature,
      secret,
    });
  } catch {
    return new Response("Invalid signature", {
      status: 401,
    });
  }

  await processVerifiedEvent(event);

  return new Response("Received", {
    status: 200,
  });
}

verifyWithProviderSdk and processVerifiedEvent are placeholders, not built-in JavaScript functions. Implement them using the provider's official documentation and your own event-processing service.

Do not skip signature verification in production just to make local testing easier.

Reference: OWASP Webhook Security Cheat Sheet.

11. Handle duplicate webhook events

Webhook providers may retry deliveries when your endpoint is unavailable or does not acknowledge an event successfully.

This means the same logical event can reach your application more than once.

Consider this scenario:

  1. A payment-completed event arrives.
  2. Your application updates the order.
  3. Your application fails before returning a successful response.
  4. The provider retries the delivery.
  5. The same event arrives again.

If the handler blindly repeats the business operation, it might send multiple emails, update records repeatedly, or trigger other unwanted side effects.

Maintain an event-processing record

A common solution is to store processed event identifiers.

For example:

webhook_events
--------------
id
provider
event_id
event_type
status
received_at
processed_at

A useful uniqueness constraint can prevent the same provider event from being accepted as a new independent event.

The general flow becomes:

Receive webhook
      |
      v
Verify signature
      |
      v
Check event ID
      |
      +---- Already processed?
      |          |
      |          v
      |      Acknowledge safely
      |
      v
Persist event or queue it
      |
      v
Process business operation
      |
      v
Record final status

The database operation that claims an event must be concurrency-safe. Two identical deliveries can arrive at almost the same time.

Use a unique database constraint or equivalent atomic mechanism instead of relying only on an application-level check.

Also distinguish between an event that is received, durably queued, processing, successfully processed, and failed. This makes retries and recovery easier to reason about.

12. Process webhooks asynchronously when appropriate

A webhook endpoint should not perform a long sequence of operations before acknowledging a valid event.

For example, a payment webhook might need to:

  • Validate the event.
  • Update a database record.
  • Send an email.
  • Update analytics.
  • Trigger another service.

Some of these operations may take time or fail independently.

For a larger workflow, a safer architecture is:

Webhook provider
      |
      v
Webhook endpoint
      |
      v
Signature verification
      |
      v
Persist event safely
      |
      v
Return successful acknowledgement
      |
      v
Background worker
      |
      +---- Update order
      |
      +---- Send notification
      |
      +---- Update related records
      |
      v
Record processing result

The event should be durably persisted or queued before acknowledging it. Otherwise, your endpoint could return success and then lose the event before processing.

Use a queue, job system, or durable event-processing mechanism appropriate to your infrastructure.

For small applications, synchronous processing may be sufficient if the work is quick and reliable. Choose based on the provider's timeout expectations, the complexity of the operation, and the recovery requirements.

13. Protect integrations against unsafe API responses

Developers often focus on securing requests sent to external services. But responses received from those services also need to be treated carefully.

Even a trusted provider can return unexpected, malformed, incomplete, or outdated data.

Validate the response before using it.

For example, if your application expects a payment status, do not assume every string returned by the provider is a valid state.

Use an explicit mapping:

type PaymentStatus =
  | "pending"
  | "completed"
  | "failed"
  | "cancelled";

function normalizePaymentStatus(
  value: unknown
): PaymentStatus | null {
  if (typeof value !== "string") {
    return null;
  }

  const allowed: PaymentStatus[] = [
    "pending",
    "completed",
    "failed",
    "cancelled",
  ];

  return allowed.includes(value as PaymentStatus)
    ? (value as PaymentStatus)
    : null;
}

This example checks a small set of permitted states. A production implementation should also validate the complete response structure and handle unknown provider states deliberately.

Other useful precautions include:

  • Validate expected content types.
  • Limit payload sizes.
  • Handle missing fields.
  • Avoid rendering untrusted HTML.
  • Do not trust provider-supplied URLs without validation.
  • Apply authorization before exposing retrieved data to users.
  • Avoid automatically fetching arbitrary URLs returned by an external service.

OWASP identifies unsafe consumption of APIs as a distinct API security risk. External responses should not receive more trust simply because they came from a familiar service.

Reference: OWASP API Security Top 10.

14. Handle rate limits and service availability

External providers often restrict how frequently your application can make requests.

If you exceed the limit, the provider may return HTTP 429.

A reliable integration should:

  1. Recognize rate-limit responses.
  2. Respect Retry-After when supplied.
  3. Avoid retrying immediately in a tight loop.
  4. Limit concurrent requests.
  5. Cache suitable responses when the data allows it.
  6. Use queues for work that can be delayed.
  7. Provide a useful experience when the service is temporarily unavailable.

For example, a weather application does not necessarily need to request the same location's forecast every time a user opens the dashboard. Caching may reduce requests and improve response time, provided the freshness requirements are respected.

Do not cache sensitive data or data that should not be shared between users. Cache keys and authorization boundaries must be designed carefully.

15. Monitor integration health after deployment

An integration can pass every test and still fail later.

Provider outages, expired credentials, API changes, network issues, and quota limits can affect production behavior.

Monitor the signals that help you detect problems.

SignalWhy it matters
Request success rateShows whether calls are completing
Request latencyIdentifies slow external services
Timeout countReveals connectivity or provider problems
HTTP 429 countShows rate-limit pressure
Authentication failuresMay indicate expired or incorrect credentials
Webhook delivery failuresShows whether incoming events are being accepted
Duplicate event countHelps detect retries or duplicate deliveries
Queue depthReveals processing delays
Failed job countIdentifies work that needs recovery

Use structured logs with a correlation ID or request ID where possible. This helps connect an application operation to an external request and any resulting webhook.

Avoid logging authorization headers, API keys, full payment details, or unnecessary personal information.

Set alerts for meaningful failures rather than sending a notification for every individual error.

16. Test integrations before production

A good integration needs tests for successful behavior and failure scenarios.

Use the provider's sandbox or test environment wherever available.

API integration tests

  • Valid credentials allow the expected request.
  • Missing credentials fail safely.
  • Invalid input is rejected.
  • Unauthorized users cannot trigger protected operations.
  • Unexpected response formats are handled.
  • Timeouts do not crash the application.
  • Rate limits are handled appropriately.
  • Retries do not create duplicate operations.

Webhook tests

  • Missing signatures are rejected.
  • Invalid signatures are rejected.
  • Valid provider events are accepted.
  • Duplicate event IDs do not repeat side effects.
  • Concurrent duplicate deliveries are handled safely.
  • Invalid or oversized payloads are rejected.
  • Processing failures can be recovered.
  • Event ordering assumptions are tested or avoided.

Operational tests

  • Test and production credentials are separated.
  • Secrets are not exposed in browser code or logs.
  • Provider errors produce useful application behavior.
  • Important failures are observable.
  • Credentials can be rotated.
  • API version changes can be reviewed safely.

Never test payment flows using real customer charges or production records unless you have a controlled, explicitly authorized procedure.

17. Ask AI coding agents to build integrations safely

Now that the architecture and reliability requirements are clear, AI coding agents can help implement the integration.

The key is to give the agent the provider documentation, the application context, and clear acceptance criteria.

Prompt 1: Research and plan the integration

I want to integrate [PROVIDER NAME] into this application.

Before writing code:

1. Inspect the existing repository and project instructions.
2. Review the provider's official documentation.
3. Identify the authentication method and required scopes.
4. Identify the required endpoints and data formats.
5. Identify rate limits, timeouts, and retry behavior.
6. Identify webhook requirements if applicable.
7. Identify security and data-handling requirements.
8. Identify the existing architecture where this integration belongs.

Prepare an implementation plan covering:
- Files and components to create or modify
- Environment variables required
- API request and response handling
- Authentication and authorization
- Error handling and retries
- Webhook verification and idempotency
- Tests and acceptance criteria

Do not invent provider capabilities or API parameters.
Cite the official documentation used.
Do not modify files until the plan is reviewed.

Prompt 2: Implement the API integration

Implement the approved integration plan for [PROVIDER NAME].

Requirements:

- Follow the existing project architecture.
- Keep private credentials server-side.
- Use the provider's official authentication method.
- Validate incoming and outgoing data.
- Use request timeouts.
- Handle expected HTTP error responses.
- Apply retries only when safe and supported.
- Avoid exposing raw provider errors to users.
- Use structured logging without sensitive values.
- Avoid unnecessary dependencies.

Add tests for successful requests, invalid inputs,
authentication failures, timeouts, and provider errors.

Do not replace real functionality with mock responses.
Do not change unrelated features.
Report changed files and verification results.

Prompt 3: Implement webhook handling

Implement webhook handling for [PROVIDER NAME].

First inspect the official webhook documentation.

The implementation must:

1. Read the request body in the format required for signature verification.
2. Verify the signature using the provider's recommended library.
3. Reject invalid deliveries.
4. Validate the event structure.
5. Persist event IDs safely.
6. Prevent duplicate processing.
7. Handle concurrent deliveries.
8. Process events in a recoverable manner.
9. Handle retries and out-of-order events according to provider guarantees.
10. Avoid logging secrets or sensitive payloads.

Add tests for invalid signatures, duplicate events,
concurrent deliveries, malformed payloads, and failures.

Do not invent signature headers or verification algorithms.
Do not claim the endpoint is secure without verification.

Prompt 4: Review integration security

Act as an independent integration security reviewer.

Review the complete integration and its surrounding code.

Check:
- Credential storage and exposure
- Authentication and authorization
- OAuth state and token handling, if applicable
- Request validation
- Response validation
- SSRF risks where URLs are fetched dynamically
- Webhook signature verification
- Replay and duplicate-event handling
- Idempotency
- Rate limiting
- Timeout and retry behavior
- Sensitive logging
- Data privacy
- Dependency risks

For every finding, provide:
- Severity
- Evidence and affected code location
- Realistic failure or attack scenario
- Recommended fix
- Regression test

Separate confirmed vulnerabilities from suggestions
and issues that need more context.

Do not modify files during the review.

Prompt 5: Verify the complete integration

Verify the integration end to end.

Run the relevant:
- Unit tests
- Integration tests
- Webhook tests
- Type checks
- Lint checks
- Security scans
- Production build

Test success and failure scenarios.

Inspect the final code changes and confirm:
- No credentials are exposed.
- Protected operations enforce authorization.
- Duplicate operations are controlled.
- Provider failures are handled safely.
- Events can be recovered when processing fails.

Report the exact commands executed, their results,
and any remaining manual verification.

Do not invent test results or claim unverified behavior.

Remember that AI-generated code and AI-generated security reviews are not independent proof. Use provider tooling, automated tests, source review, and appropriate human approval.

18. Common integration mistakes to avoid

Putting API keys in frontend code

Private credentials should stay on the server. A frontend environment variable is not automatically secret.

Trusting webhook JSON without verifying its signature

A request body that looks like a payment-completed event is not proof that the payment provider sent it.

Retrying every failed request

Some operations may have succeeded even if the response was lost. Retry only with an appropriate duplicate-protection strategy.

Processing duplicate events as new operations

Use durable event records and concurrency-safe deduplication.

Ignoring provider rate limits

Repeated requests can make an outage worse and may result in temporary or permanent access restrictions.

Trusting every external response

Validate returned data before using it in business logic or showing it to users.

Building integrations without a sandbox

Use provider test environments to verify behavior without affecting real accounts or customers.

Ignoring API version changes

External services evolve. Monitor deprecation notices and review version upgrades before they affect production.

Allowing the AI agent to invent API details

Give it official documentation and ask it to identify missing information instead of guessing endpoint names, payload fields, or authentication rules.

19. A practical integration launch checklist

Before enabling an integration in production, review these items.

Planning

  • Provider documentation reviewed.
  • Required features and API permissions identified.
  • Data flow documented.
  • Integration boundaries defined.

Credentials and security

  • Secrets stored securely.
  • No private credentials in client-side code.
  • Permissions and scopes are limited.
  • Inputs and external responses are validated.
  • Sensitive information is not logged.

Reliability

  • Request timeouts configured.
  • Retry behavior documented.
  • Idempotency implemented where supported and needed.
  • Rate limits handled.
  • Webhook signatures verified.
  • Duplicate events handled.
  • Event processing can recover from failures.

Testing and deployment

  • Sandbox tests completed.
  • Failure scenarios tested.
  • Automated checks pass.
  • Production credentials configured separately.
  • Monitoring and alerts configured.
  • Rollback or recovery procedure documented.

Frequently asked questions

Should third-party API calls happen in the frontend or backend?

Public, non-sensitive APIs may be called directly from a browser when their design permits it. Requests requiring private credentials, privileged access, or server-side authorization should normally go through your backend.

What is the difference between a webhook and an API?

An API request is usually initiated by your application to retrieve or modify information. A webhook is an event notification sent by another system to your application when something happens.

Why are webhook events delivered more than once?

Providers may retry delivery when they do not receive an expected acknowledgement. Network failures and processing errors can also cause repeated delivery. Design handlers to tolerate duplicates.

Is a successful HTTP response enough to confirm a payment?

Not necessarily. Use the provider's documented payment lifecycle and verify the authoritative payment status. Do not trust a browser redirect or frontend success message as the sole proof of payment.

Should every failed API request be retried?

No. Retry only when the failure is temporary and the operation can be repeated safely. Follow the provider's documented retry behavior and use idempotency where supported.

Can AI coding agents securely implement OAuth and webhooks?

They can help implement them, but you must provide the official specifications, review the security-sensitive code, and test important attack and failure scenarios. Do not assume generated code is secure just because it works in a demonstration.

How should I handle an external provider outage?

Use timeouts, bounded retries, queues where appropriate, useful user-facing messages, and monitoring. Some operations should be delayed for later recovery rather than failed permanently.

Final thoughts

Third-party integrations are where an application starts depending on systems you do not control.

That makes reliability and security just as important as the initial implementation.

A successful API request is only the beginning. You also need to protect credentials, validate responses, handle failures, respect rate limits, verify webhooks, prevent duplicate operations, and monitor the integration after deployment.

AI coding agents can make this work faster, but they need clear boundaries and accurate provider documentation.

Start with a small integration, test it in a sandbox, and build the reliability requirements into the design rather than adding them after something breaks.

Connect carefully. Handle failures deliberately. Trust only what you verify.


Continue the Series

If you're building applications with AI coding agents, continue with these guides:

  • The Ultimate Pre-Vibe-Coding Checklist: Prepare your project before writing the first prompt. Read here
  • AI Agent Rules for Vibe Coding: Use AGENTS.md and supporting Markdown files to give coding agents reliable project context. Read here
  • The UI/UX Checklist for Vibe-Coded Applications: Improve usability, accessibility, responsive layouts, and real-world interactions before shipping. [Use the published article URL.]
  • The Complete Vibe Coding Starter Kit: Bring project rules, reusable prompts, and development workflows together. Read here
  • Automating Testing and Security with AI Coding Agents: Learn how to verify AI-generated code using automated tests, security checks, and code reviews. Read here
  • Coming next: SEO and A/B Testing for AI-Built Applications. Learn how to improve search visibility, measure user behavior, and experiment with changes that improve your application.

Was this post helpful?

Comments

Be the first to comment

Be the first to share your thoughts.