Technical

How to Submit Contact Form 7 Data via REST API

Introduction:

Contact Form 7 is the most popular and widely used WordPress plugin. It works perfectly for standard form submissions, but in advanced use cases contact form-7 often requires programmatic submissions via the REST API.  Contact Form – 7 can now be integrated with custom forms, CRM’s and third-party services, you can use Contact Form Rest API to send form submissions securely.

What is a REST API?

A REST API (Representational State Transfer – Application Programming Interface) is a method that enables different applications to communicate with each other over the internet using a set of defined rules.

REST is an architectural approach that specifies how data should be accessed and transmitted.

API acts as a connector that lets two systems—whether applications, servers, or services—exchange information.

When working with a REST API, you usually rely on standard HTTP methods, such as:

GET → Fetch data

POST → Add or send new data

PUT/PATCH → Modify existing data

DELETE → Remove data

Benefits of Using the Contact Form 7 REST API

1. Fill out forms anywhere – Data can be sent using CF7 forms from external platforms, mobile apps, or websites.

2. Frontend design flexibility – Use React, Vue, or other frameworks to create bespoke forms, and let CF7 manage submissions.

3. Easy integrations – Connect to automation systems, email tools, and CRMs with ease.

4. Simple error handling –  Get organized answers that indicate validation problems or success.

5. Safe and consistent –  Use WordPress and HTTPS safeguards to keep data safe while applying the same validation guidelines everywhere.

Step-1 : Exploring the Contact Form 7 REST API

A REST API endpoint has been provided by every CF7 form:
https://yourdomain.com/wp-json/contact-form-7/v1/contact-forms/{form_id}/feedback

1. Open the form in the WordPress admin.

2. Look at the browser’s address bar.

3. The URL will look like this:

4. The number after post = (13230 in this image) is your FORM ID.

5. Use this ID in your API endpoint:
Method: POST
https://yourdomain.com/wp-json/contact-form-7/v1/contact-forms/
13230/feedback

{form_id} – This is the form’s WordPress database ID, not its shortcode ID. It is located in the WordPress admin URL while the form is being edited.

Approach: POST

Types of Content: application/x-www-form-urlencoded or application/json

For public forms, authentication is optional; if the website limits access to the API, it is necessary.

Step-2 : Preparing Form Data

1. The field names in your request must exactly match the form fields specified in CF7 when sending data to the Contact Form 7 REST API.

2. CF7 identifies each input by its field name (not the label). If the names don’t match, the submission will fail or return a validation error.

3. Example CF7 Form:
Suppose your form contains these fields:

4. Example HTML Form:


<form class="contact-form" id="contactForm">
  <div class="form-group">
    <label for="name">Name *</label>
    <input type="text" id="name" name="your-name" placeholder="Name *" required>
  </div>

  <div class="form-group">
    <label for="phone">Phone *</label>
    <input type="tel" id="phone" name="your-phone" placeholder="Phone *" required>
    <span id="phone-error" style="color:red; display:none;">
      Please enter a valid phone number
    </span>
  </div>

  <div class="form-group">
    <label for="email">Email</label>
    <input type="email" id="email" name="your-email" placeholder="Email">
  </div>

  <button type="submit" class="submit-btn" id="submitBtn">Submit</button>
</form>

5. your-name, your-email, your-message, and your-file are the field names.

6. You must use these exact names when sending data via the API.

Step-3 : Submitting Data via REST API

1. Using JavaScript (Fetch API)


<script>
async function submitCF7Form() {
  const formData = {
    "your-name": "John Doe",
    "your-email": "john@example.com",
    "your-message": "Testing CF7 REST API submission"
  };

  try {
    const response = await fetch('https://yourdomain.com/wp-json/contact-form-7/v1/contact-forms/123/feedback', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    });

    const result = await response.json();

    if(result.status === 'mail_sent') {
      console.log('Form submitted successfully!');
    } else if(result.status === 'validation_failed') {
      console.error('Validation errors:', result.invalid_fields);
    } else {
      console.error('Submission failed:', result.message);
    }
  } catch (error) {
    console.error('Network or server error:', error);
  }
}

submitCF7Form();
</script>

Note: https://yourdomain.com/wp-json/contact-form-7/v1/contact-forms/123/feedbackReplace {form_id} with your actual form ID. You can find the form ID in the URL when editing the form in WordPress, e.g., post=14498.

2.  Using PHP (cURL)


$form_id = 123;
$url = "https://yourdomain.com/wp-json/contact-form-7/v1/contact-forms/{$form_id}/feedback";

$data = [
    'your-name' => 'John Doe',
    'your-email' => 'john@example.com',
    'your-message' => 'Hello from PHP via CF7 API'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if($result['status'] === 'mail_sent') {
    echo "Form submitted successfully!";
} elseif($result['status'] === 'validation_failed') {
    print_r($result['invalid_fields']); // Handle errors
} else {
    echo "Submission failed: " . $result['message'];
}

Step 4: Handling Validation and Errors

CF7 REST API returns structured JSON responses:


          {

  "status": "validation_failed",

  "invalid_fields": [

    {"name": "your-email", "message": "Email is required."}

  ],

  "message": "Validation errors occurred."

}


Note: Always verify the status (mail_sent, mail_failed, validation_failed) before processing a response, show errors in your custom forms next to the corresponding fields, and keep track of every response to troubleshoot server problems.

Step 5: Authentication & Security

Even though CF7 forms are public by default, advanced integrations require security:

1. HTTPS – Always use encrypted connections.

2. WordPress Nonce – Validate requests originating from your site.

3. JWT Authentication – Use JWT Authentication for WP REST API plugin for secure API submissions.

4. Restrict Access – Limit API access to specific IPs or roles using functions.php.

Step 6: Debugging & Error Handling

1. To facilitate development, enable WordPress WP_DEBUG.

2. Log API responses so you may debug them.

3. Make sure your mobile app or front-end handles server-side errors appropriately.

Conclusion:

Advanced form handling in WordPress is made possible by the Contact Form 7 REST API. The API allows you to submit forms from any frontend or application, interact with email tools, CRMs, and third-party services with ease, and provide uniform security and validation for all submissions.

Whether your forms are submitted via a website, mobile app, or bespoke application, their dependability depends on your ability to recognize your form ID, accurately prepare field data, handle API responses, and implement appropriate authentication.

Leave a comment

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