Introduction
A third party API allows your WordPress site to communicate with an external service , payment gateways, CRMs, Lead services, social platforms, shipping providers, etc. Data is sent and received over HTTP in serialised formats such as XML or JSON.
An awareness of the appropriate third-party API integration methods is vital for ensuring the construction of scalable, secure WordPress applications. There are a plethora of connection methods that WordPress offers, each of which is relevant for different scenarios. This guide covers all five major methods with working code examples.
Whether you need to learn how to integrate third-party APIs for a custom plugin or a client project, this guide walks you through every approach, from the built-in WordPress HTTP API to JavaScript-based async calls.
What this guide covers
-
How to integrate third party APIs using WordPress-native methods
-
Types of API integration methods — from server-side to frontend
-
REST vs GraphQL vs Webhooks — key differences explained
-
Best API integration method for different application scenarios
-
Security best practices, caching, and error handling
Related reading: How to Connect Third-Party APIs in WordPress | FastAPI Authentication Security with Token
Method 1 — WordPress HTTP API WordPress HTTP API
[ MOSTY RECOMMENDED ]
wp_remote_get() and wp_remote_post()
The built-in WordPress way. Handles timeouts,redirects, SSL and errors automatically. Always prefer this over raw cURL in WordPress projects. This is the most widely used of all third party API integration methods for WordPress.
GET request example
$response = wp_remote_get( 'https://api.demo.com/data', [
'timeout' => 15,
'headers' => [
'Authorization' => 'Bearer YOUR_API_KEY',
'Accept' => 'application/json',
],
] );
if ( is_wp_error( $response ) ) {
error_log( $response->get_error_message() );
return;
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
POST request example
$response = wp_remote_post( 'https://api.demo.com/submit', [
'timeout' => 15,
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer YOUR_API_KEY',
],
'body' => json_encode([
'name' => 'John Doe',
'email' => 'john@example.com',
]),
] );
$status = wp_remote_retrieve_response_code( $response );
$body = json_decode( wp_remote_retrieve_body( $response ), true );
Tip: Store API keys in wp-config.php using define() — never hardcode them in theme or plugin files.
Method 2 — PHP cURL
[ ALTERNATIVE ]
Direct cURL calls
Use cURL when you are building a standalone PHP script outside WordPress, or need low-level control over the request that wp_remote_* does not expose. This is among the more traditional types of API integration methods in PHP.
$ch1 = curl_init('https://api.aidemo.com/data');//yourapi url comes here
curl_setopt_array($ch1, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_KEY',
'Accept: application/json',
],
]);
$response_data = curl_exec($ch1);
$http_code_st = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch1);
curl_close($ch1);
if ($curl_error) {
error_log('Request failed: ' . $curl_error);
return null;
}
if ($http_code !== 200) {
error_log('Unexpected status code: ' . $http_code_st);
return null;
}
$result_data = json_decode($response_data, true);
Warning: Inside WordPress always prefer wp_remote_get() over cURL. cURL bypasses WordPress filters and error handling hooks.
Method 3 — Custom REST API endpoint
[ SCALABLE ]
Register a WP REST route that proxies the third party API
Make your own endpoint available at /wp-json/myplugin/v1/data that the frontend will call instead of directly running on the third party. Holds API keys on the server-side and allows response caching.. This is the best API integration method for applications that require frontend data access.
add_action( 'rest_api_init', function () {
register_rest_route( 'aidemoplugin/v1', '/weather', [
'methods' => 'GET',
'callback' => 'aidemoplugin_get_weather',
'permission_callback' => '__return_true',
] );
} );
function aidemoplugin_get_weather( WP_REST_Request $request ) {
$city = sanitize_text_field( $request->get_param( 'city' ) );
$response = wp_remote_get(
'https://api.openweathermap.org/data/3.5/weather'
. '?q=' . urlencode( $city )
. '&appid=' . WEATHER_API_KEY
);
if ( is_wp_error( $response ) ) {
return new WP_Error( 'api_error', 'Could not fetch it,
[ 'status' => 500 ] );
}
return json_decode( wp_remote_retrieve_body( $response ), true );
}
Need help building a custom REST-based integration? Visit our custom web development services page.
Method 4 — Plugin-based integration
[ NO-CODE / LOW-CODE ]
Use existing WordPress plugins
You do not always need custom code for common services. You don’t have to worry about authentication, webhooks, and mapping your data. That’s all handled for you. This approach is perfect when speed is more important than customisation.
Popular plugin integrations
-
Integrate WordPress with 5000+ apps using Zapier / Make Webhooks
-
WPForms Includes inbuilt integration API with CRM and Email Marketing
-
API de passerelles de paiement WooCommerce (Stripe, PayPal, Razorpay)
-
FluentCRM- Brings email API integrations and marketing automation.
-
Advanced form-to-API integrations for Gravity Forms
Tip: Plugin integrations work best when speed is a higher priority than customisation. Custom code provides full control for unique business logic.
Method 5 — JavaScript fetch / AJAX
[ FRONTEND ]
wp_ajax or fetch via your custom REST endpoint
This should be used when the API call should happen after the page has loaded live search, dynamic pricing, real-time data, etc. Always use your own endpoint to proxy to hide API keys. This explains how to use third-party APIs on the client side securely.
PHP — Register the AJAX action
add_action( ‘wp_ajax_nopriv_get_rates’, ‘myplugin_get_rates’ );
add_action( 'wp_ajax_get_rates', 'myplugin_get_rates' );
function myplugin_get_rates() {
check_ajax_referer( 'myplugin_nonce', 'nonce' );
$data = /* call third party API here */;
wp_send_json_success( $data );
}
The above code snippet is with reference to using WP Ajax with WordPress Plugins to call a third-party API.
JavaScript — Call from the browser
fetch( ajaxurl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
action: 'get_rates',
nonce: myPlugin.nonce,
}),
})
.then( r => r.json() )
.then( data => console.log( data.data ) );
follows on from r to convert json
Then Using DATA only to Log response
REST API vs GraphQL vs Webhooks
The most frequently asked question while integrating APIs is whether to go for REST API vs GraphQL vs webhooks. Below is a detailed comparison:
| REST | GraphQL | Webhooks | |
| Request type | Client pulls data | Client queries exactly what it needs | Server pushes data |
| Best for | Standard CRUD APIs | Complex, nested data | Real-time events |
| Setup complexity | Low | Medium | Medium |
| WordPress support | Built-in REST API | Via plugin (WPGraphQL) | Via plugin or custom endpoint |
| Use case example | Weather API, payment gateway | Headless WordPress | Order notifications, form submissions |
Which method should you use?
| Situation | Best method | Reason | Best for | Reference |
| Server-side in WordPress | wp_remote_get/post | Native, handles errors automatically | All WordPress projects | Method 1 |
| Standalone PHP script | cURL | Full control, no WordPress dependency | CLI scripts, non-WP PHP | Method 2 |
| Frontend / async call | fetch + REST proxy | Keeps API keys server-side | Live search, dynamic data | Method 5 |
| No custom code needed | Plugin / Zapier | Fast setup, no coding required | Small sites, quick integrations | Method 4 |
| Expose data to frontend | Custom REST endpoint | Scalable, cacheable, secure | Headless, SPAs, apps | Method 3 |
Best practices & security tips
1. Store API Keys Safely
Store API keys in wp-config.php as a constant and never include them in source control files.
// In wp-config.php
define( 'MY_LEADAPI_KEY', 'your-secret-key-here' );
// In your plugin/theme
$key = MY_LEADAPI_KEY;
2. Cache API responses with transients
PI requests will slow your site down, which you can prevent by caching results using the transient API to cache the API data.
$cached = get_transient( 'myplugin_api_data' );
if ( false === $cached ) {
$response = wp_remote_get( 'https://api.aidemo.com/data' );
$cached = json_decode(
wp_remote_retrieve_body( $response ), true
);
set_transient( 'myplugin_api_data', $cached, HOUR_IN_SECONDS );
}
return $cached;
Tip: Using transients for caching is one of the most significant optimizations you can make when integrating third-party APIs with your WordPress website.
3. Sanitise and validate all data
- Sanitize data before putting it into API URL or body request
- Check for HTTP status codes before processing responses
- Use is_wp_error() function to handle failures and error_log() to log errors
- Always assume that data from other parties might be malicious or invalid
4. Handle errors gracefully
$response = wp_remote_get( 'https://api.aidemo.com/data' );
// Check for WordPress-level errors
if ( is_wp_error( $response ) ) {
error_log( $response->get_error_message() );
return false;
}
// Check HTTP status code
$code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $code ) {
error_log( 'API returned status: ' . $code );
return false;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
Conclusion
If you’re using WordPress as your platform for developing website(s) then you likely know how versatile it is when it comes to integrating with any sort of 3rd party APIs (like Google Maps API or Twitter API). Most WordPress development will ultimately utilize 2 primary functions from WordPress’ core libraries when interfacing with 3rd party APIs – wp_remote_get() and wp_remote_post(). Both are secure, have been tested extensively and will play well together with existing built-in error handling mechanisms already provided by WordPress.
A complete understanding of all the possibilities available to integrate with a 3rd party API is critical (especially knowing which type of API integration you will utilize – http request, REST API Proxy, no code plugin) so that you can select the right type for YOUR project. When you need to provide an interface for displaying API data on your website create a custom REST API proxy to keep your API key(s) secure.
Adding transient caching to your API integration will provide you with a high-volume, production-ready solution that will scale as your project grows. If you’re building out complex API integrations and working with an experienced partner on custom website development you will save both time and risk.
Tip: Start simple by using wp_remote_get(), follow it up with set_transient() to cache your API’s response, and finally create a custom REST API proxy when your users need access to your API resource – this process will solve 90% of all real-world API integration problems.
Further reading: How to Connect Third-Party APIs in WordPress | FastAPI Authentication Security with Token
Most frequently asked question in FAQ
There are several different ways to add an API to a website:
You can use one of the following methods that allow you to integrate 3rd Party APIs with your WordPress site: PHP cURL; WordPress built-in HTTP API functions (ex: wp_remote_get() & wp_remote_post()); creating custom REST endpoints; and/or using AJAX calls (via JavaScript (Fetch API or other browser based JS Libraries) or via AJAX calls using jQuery AJAX) alone or in combination with each other.
The decision on a method for adding APIs to a WP site will depend on both the project’s needs and how and where to interface with the API—either via the WordPress backend or front-end. The complexity—low-code or custom coding—of your application will factor in whether you can utilize existing WP functions or if you will have to develop your own solution to access the API.