Recent searches


No recent searches

Can I attach files to tickets using the API?



Edited Dec 04, 2023


-1

25

25 comments

Hi, is it possible to attache a file from external resource, smth like Google Cloud Bucket, or Azure Blob Storage? Since, I do not have the file on the server I am not able to upload it.

1


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi Віктор Борисюк,

Thanks for reaching out!

Unfortunately it's not possible to attach files to a ticket comment directly from an external source. The file must be uploaded via the Attachment API which requires the actual file, which then creates a token that is used to attach the file to the ticket. 

An alternative option could be uploading the file as an inline attachment using markdown, depending on the file type.

Feel free to reach out if you have any questions!

Tipene

0


Tipene Hughes I'm trying to do this exact thing. We have Power Apps forms that create SharePoint lists, in which we then use the Zendesk API to create the ticket in Zendesk. I'm wondering about the best approach to get the attachment into the ticket, or at the very least, a link to the attachment? 

I've found this article online, but am having a hard time understanding the 'Attachment' section:

https://4sysops.com/archives/using-the-zendesk-api-with-microsoft-power-automate/

 

Thanks in advance,

Chris

1


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hey Chris,

I'm not super familiar with Microsoft Power Apps but from the looks of it, the article is outlining how to utilize the Attachments API along with the Tickets API within the Power Apps UI.

When uploading an image to create a token using the Attachments API, the file must first be converted to binary which appears to be something that can be handled within Power Apps. Once the token has been generated, it's then passed in to the payload sent to the Tickets API to create or update a ticket which again looks like it can be handled within the Power Apps UI. 

Sorry I can't give you any specifics on the functionality of Power Apps but by the looks of it, the article is outlining the correct workflow as written in the documentation I linked above. 

 

0


Hello Tipene Hughes, sorry for hijacking this thread, but I am currently stuck and I desperately need some help.

I am currently developing an app that has 2 fields, a file upload field that allows multiple files and a text area.

Here is the current status of the app:

  • I was able to create a private comment using the value inputted on the text area
  • I was able to get the token when I uploaded the files using the Upload API

The next goal is for all the files to be attached to the ticket. I am using this as my reference and on the examples, only 1 file is attached to the ticket comment.

Can you help to confirm if it is possible to attach multiple files/images to 1 ticket comment? If yes, can you point me in the right direction?

Thank you,
Benessa

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hey, Benessa Mae Dumol!

Can you confirm if you're passing in the token as a query parameter to the endpoint URL when uploading more than one attachment? This is referenced in the documentation here.

 

0


HI Tipene Hughes, thank you for responding to my comment.

Currently, I am looping through all the files that were uploaded to get all the tokens.

I am using this endpoint /api/v2/uploads.json?filename=attachment.jpg to get the upload token. Below is my for loop code to get all the tokens.

for (let i = 0; i < incidentAttachmentLength; i++) {
      const settings = {
        url: "/api/v2/uploads.json?filename=attachment.jpg",
        type: "POST",
        contentType: "application/binary",
        cors: false,
        secure: true,
        httpCompleteResponse: true,
        data: files[i].name
      };
 
      client.request(settings).then(
        function(response) {
          json = JSON.parse(response.responseText);
          console.log("token: " + json.upload.token);
        },
        function(response) {
          console.error(response.responseText);
        }
      );
    }

I am also using the endpoint /api/v2/tickets/ to create the ticket comment. Below is my code to create the ticket comment.

const settings = {
    url: "/api/v2/tickets/" + zendeskTicketId,
    type: "PUT",
    cors: false,
    secure: true,
    httpCompleteResponse: true,
    data: {
      "ticket": {
        "comment": {
          "body": ticketComment,
          "uploads": uploadToken,
          "public": false
        },
      }
    },
  };

  client.request(settings).then(
    function(response) {
      console.log("Comment posted.")
    },
    function(response) {
      console.error(response.responseText);
    }
  );
 
Is it possible to pass the array of upload tokens on the uploads parameter on the create ticket comment API?

Thank you,
Benessa

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi Benessa Mae Dumol,

You only need to generate one token which you'll then use to make subsequent requests to the uploads API endpoint to add additional attachments.

After making the first request to the uploads endpoint, you will need to add the token to the end of the URL for subsequent uploads e.g:

"https://{subdomain}.zendesk.com/api/v2/uploads?filename=user_crash.log&token={optional_token}"

Then, using just the single token, you'll make the call to the tickets API which will upload all attachments that have been associated with the token.

I hope this helps! Feel free to reach out with any questions.

Tipene

0


Hi Tipene Hughes,

It seems that I am not passing the correct data on the /api/v2/uploads.json?filename=attachment.jpg API endpoint. Currently, I am passing the filename and when it was uploaded and attached to the ticket I am getting the error Error loading image when I tried opening the attached file.

I also tried passing Binary and Base64 data but I am getting the error

{
    "readyState": 4,
    "responseText": "{\"error\":\"AttachmentUnprocessable\",\"description\":\"Attachment file could not be processed.\"}",
    "status": 422,
    "statusText": "error"
}

May I ask what is the correct data format that I need to pass on the data parameter? 

Appreciate your response.

Thank you,
Benessa

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi Benessa,

Can you try changing the ContentType header value on the settings object of the /api/v2/uploads.json call to "image/jpg". Also, be sure to correctly match the filename extension in the URL query parameter with the filename extension of the actual file being uploaded.

Let me know if that helps!

Tipene

0


Hi Tipene Hughes,

Thanks for the suggestion. I changed it to image/jpg and made sure that the filename extension in the URL query parameter and the filename extension of the actual file being uploaded is the same but I am still getting the same error.

{
    "readyState": 4,
    "responseText": "{\"error\":\"AttachmentUnprocessable\",\"description\":\"Attachment file could not be processed.\"}",
    "status": 422,
    "statusText": "error"
}

I tried uploading Binary and Base64 data of the images uploaded for contentType: "application/binary" and jpg images for "image/jpg" but still no luck.

I hope you still have some suggestions that I can try. Appreciate your response.

Thank you,
Benessa

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi Benessa,
 
I've done some more digging and it unfortunately appears that you cannot upload attachments using the client.request method - you'll need to make the request via the Fetch API or something similar. Here's a working example of how that might look:
 
var client = ZAFClient.init();

const sendAttachment = async () => {

const file = await fetch("./logo.png");
const content = await file.blob();

const request = await fetch("https://{subdomain}.zendesk.com/api/v2/uploads.json?filename=logo.png", {
method: 'POST',
headers: {
'Content-Type': 'application/binary',
'Authorization': 'Basic ABC123'

},
body: content
});
const response = await request.json()
console.log(response)

const ticketSettings = {
url: "/api/v2/tickets/{ticket_id}",
type: "PUT",
cors: false,
secure: true,
httpCompleteResponse: true,
data: {
ticket: {
comment: {
body: "Hello, World",
uploads: [response.upload.token],
},
},
},
};

console.log(ticketSettings);

client.request(ticketSettings).then((data) => console.log(data));
};
 
Let me know if this helps and if you have any questions, feel free to reach out!
 
Tipene

1


Hi Tipene Hughes, thank you for the patience and for looking deeper into this question.

Can you confirm if the working example that you provided can be used on multiple images?
I am currently using a file upload field that allows multiple files to be uploaded.

Appreciate your response.

Thank you,
Benessa

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi Benessa,
 
You'll need to update the code slightly to fit your use case, but yes, in general it should work as intended using the Fetch API or something similar.
 
Thanks!
 
Tipene

0


Hello Tipene Hughes

Happy to inform you that I was able to make my code work.

Thank you for your help.

~ Benessa

0


Why isn't this supported in the ZAF Client? Yes, you can use the fetch api but then you need the authorization header in plaintext code... Stupid security risk.

0


Hello,

Will you update the client.request() method so that it can upload an image directly ?

I tried with the fetch request but I don't know how to get the bearer token to pass ? Also I got CORS issues trying to access my domain from my iframed app ?

Can you help ?

 

0


image avatar

Sabra

Zendesk Customer Care

Hey folks! Based on the questions being asked, I wanted to make sure you were aware of our Developer Support team. They have more in-depth knowledge of our platform tools and will be able to get you the best possible answers and solutions. This team works out of our Developer Support community, which will also give you the opportunity to have other developers to share their insight as well! To get in touch, please go to the community and include as much relevant information in your post as you feel comfortable sharing. 

0


Hello,

With the example from above and the current attachment token I always get the following error message back:

{
    "error": "RecordInvalid",
    "description": "Record validation errors",
    "details": {
        "base": [
            {
              "description": "Uploads is invalid"
            }
        ]
    }
}

API Request:

{
 "ticket": {
   "comment":  { "body": "See PDF.", "uploads":  ["i2duiFM7GNcgJxo48HJWJFoA1"] }
 }
}

 

Any recommondations or advices ?

 

Thanks !

Best regards,

Marcus

0


image avatar

Christopher Kennedy

Zendesk Developer Advocacy

Hi Marcus,
 
The token value itself may be invalid for some reason.  To test this, can you successfully create/update the ticket with an empty uploads array?
 
{

  "ticket": {

   "comment":  { "body": "See PDF.", "uploads":  [] }

  }

0


Hi,
I want to upload the attachment for the respective ticket. Is it possible in ticket import API?
Thanks,

0


image avatar

Viktor Osetrov

Zendesk Customer Care

Hello Mahendran,
 
You can achieve it using 2 steps:
 
1. POST /api/v2/uploads 
Use this Attachment API endpoint for uploading your file. 
Curl sample: 
curl "https://{subdomain}.zendesk.com/api/v2/uploads?filename=user_crash.log&token={optional_token}"
Payload example:
{
"upload": {
"token": "abc123...",
...
}
}
 
2. PUT /api/v2/tickets/{ticket_id}
Use this Ticket API endpoint for updating your ticket. 
Example payload
{
"ticket": {
"subject": "My Subject",
"comment": {
"body": "A comment with an attachment",
"uploads": ["abc123..."]
}
}
}
Please notice
- please replace your data accordingly
- the token is valid for 3 days,
- make sure to include the right content type in the headers. For example: "image/png", "text/plain", "multipart/form-data", "application/json" etc. 

Hope it helps

0


Hi all

How would this work if I am planning to do a Bulk Import with the endpoint tickets/create_many?
https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_import/.

Do use this endpoint as I get the tickets metric, am able to get the comments for the tickets, but the attachments does not come with.

This is my code:

async function getComments(ticketData) {

  for (let i = 0; i < ticketData.length; i++) {

    const ticket = ticketData[i];

    try {

      const response = await axios({

        method: 'GET',

        url: `${process.env.albinURL}/tickets/${ticket.id}/comments`,

        headers: {

          'Content-Type': 'application/json',

          Authorization: `${process.env.albinAuth}`,

        },

      });

      // Add comments to the ticket

      ticket.comments = response.data.comments;

    } catch (error) {

      console.error(`Error fetching comments for ticket ${ticket.id}:`, error);

    }

  }
}
async function createTicket(data) {

  console.log('CREATING TICKETS');

  var config = {

    method: 'POST',

    url: `${process.env.albinURL}/imports/tickets/create_many`,

    headers: {

      'Content-Type': 'application/json',

      Authorization: `${process.env.albinAuth}`,

    },

    data: data,

  };

  try {

    const response = await axios(config);

    console.log('CREATED');

    console.log(response);

    console.log(response.status);

    return response.status === 200;

  } catch (error) {

    console.log(error.response.data);

    console.log('ERROR');

    return false;

  }

}
, Albin

0


image avatar

Paolo

Zendesk Engineering

Hi Albin,
 
If you are trying to get the ticket attachments, you may use the Incremental Ticket Event Export. Sample: GET /api/v2/incremental/ticket_events.json?include=comment_events,attachments,tickets,agreements&start_time={epoch_time}.

1


Hi Paolo

Thx for the reply.

Did make the suggested api calls using postman to get data for the attachment.

However, it does look very similair to the data returned from the endpoint: tickets/${ticket.id}/comments. The data returned from this call  was added to the tickets object before bulk import it. 
This creates a ticket with comments, but the attachment does not follow with.

Am i right to assume that if I use the Incremental Ticket Event Export, I can use this data to add both comments and attachment when doing the bulk import using the endpoint; imports/tickets/create_many

Thx again, Albin

 

0


Please sign in to leave a comment.