DEV Community

Cover image for How to create a Zendesk ticket from a contact form using REST API with JavaScript
Abdulrahman Saleh Khamis
Abdulrahman Saleh Khamis

Posted on

How to create a Zendesk ticket from a contact form using REST API with JavaScript

We wanted to create a custom contact form on our website, that will automatically create a support ticket on our Zendesk support system, as soon as anyone submits that form. However, we could not find a solution that worked great for us. So we had to create our own using JavaScript, Zendesk REST API v2, and Fetch API.

Follow this Quick Start guide to get your API key, and to get a better understanding about the API documentation.

Here is the complete JavaScript snippet:

const ZENDESK_API = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const ZENDESK_EMAIL = "your_api_email@example.com";
const ZENDESK_SUBDOMAIN = "your_subdomain.zendesk.com";
const auth = Buffer.from(`${ZENDESK_EMAIL}/token:${ZENDESK_API}`).toString("base64");

const ticket = {
  ticket: {
    requester: {
      name: "John Smith",
      email: "test@example.com",
    },
    subject: "Help needed!",
    comment: { body: "Hello, I need help with your product." }
  }
};

const response = await fetch(
  `https://${ZENDESK_SUBDOMAIN}/api/v2/tickets.json`,
  {
    body: JSON.stringify(ticket),
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Basic ${auth}`
  },
  method: "POST"
});

if (response.ok) {
  return { statusCode: response.status, body: response.statusText };
} else {
  throw new Error("Error requesting Zendesk API");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)