JSON endpoint

Table of contents

It is possible to send the request for a form to a JSON endpoint. When sending in the content for each field, every field just handles like "key": "value" in the form JSON. However, content for file fields need to be decoded as base64, and accept a JSON object as content:

{
  "form_message": {
    "content": {
      "content_field_a" => "value",
      "file_field_b" => {
        "base64": true,
        "filename": "my-image.png",
        "body": "base-64-string..."
      }
    }
  }
} 

The filename key is optional. When it is not given the filename is generated randomly and the extension extracted from the base64 string, if possible.

Also accepts parameter output_as, which currently only accepts"json" as value. If this parameter is set, no html is returned, but everything needed for the payload to create a form message is returned in JSON format. This looks like this:

{
  "fields": [... meta info about all registered fields],
  "meta_hash": "... encrypted hash with metadata about the form, should be sent with json request"
}

With this you can call the following endpoint in order to create a form message through a JSON request:

POST /form_messages
Accept: application/json

{
  "form_message": {
    "content": {
      "content_field_a" => "value",
      "file_field_b" => {
        "base64": true,
        "filename": "my-image.png",
        "body": "base-64-string..."
      }
    },
    "meta_hash": "... meta hash from json"
  }
}

Recaptcha and JSON endpoints

It is possible to use Recaptcha when you send in the form request to the JSON endpoint. To do this you first determine the action name of your Recaptcha request. In a regular form, Plate handles this for you, but with a JSON request you have to do this yourself. It has to be a unique name for that page. For this example we’ll use test-1234 as the action name.

First make sure enable_recaptcha is enabled for your form and all necessary JS is loaded (See the enable_recaptcha section of this article). Then you have to fetch the Recaptcha token with JS. You do this by loading the recaptcha scripts, and fetching the token with a callback. When you have the token, you can send the request to the endpoint inside the callback

loadRecaptcha("test-1234", function(token) {
  axios({
    method: 'post',
    url: '/form_messages',
    data: {
      "form_message": {
        ... json from example
      },
      "recaptcha_action": "test-1234",
      "g-recaptcha-response": token
    }
  });
})

Need help?

Do you have any question which is not answered in this knowledge base? Contact us. We are here to help you.