Table of Contents

Interacting with Files via the API

Kristen Fiddes Updated by Kristen Fiddes

Read Time: 2 mins

In this article, we're going to cover how to use the API to interact with files that either already exist in your instance or that you are wanting to add. This functionality is beneficial in use cases such as wanting to upload customer files from retired billing systems or wanting to extract a file attachment from a ticket.

How to Upload Files

An example of the cURL command used can be found below; this can be adapted to your preferred programming language.

BEARER_TOKEN='ey...'
curl --request POST \
--header "Authorization: Bearer $BEARER_TOKEN" \
--form 'files[]=@myFile.pdf' \
https://example.sonar.software/api/files
Please note: the "ey..." in the above example should be replaced with a proper bearer token that has the necessary permissions to complete the action, such as to upload files, etc. See this document for help on obtaining a token.

The above example returns a JSON response like this:

{"files":[{"id":61,"filename":"myFile.pdf","stored":true,"failure_message":null}]}

At this stage, you could grab the result and run the mutation below to associate it with the proper assignee (e.g., account, company, ticket, etc.).

To continue with our example, we would then run the following mutation to link the new file_id (ID 61 in the example) to a fileable_type, and fileable_id, which, in our example, is Account ID 1, respectively:

mutation {
linkFileToEntity (input:{
files:{
file_id:61
}
fileable_type:Account
fileable_id:1
}) {
id
}
}

The full fileable_type list can be found at https://api.sonar.software/fileabletype.doc.html.

How to Download Files

In the event you wish to extract a file attachment from your instance, you would first need to run a query to validate the file names and then use a cURL command to download the file.

In our example, we want to see whether ticket reply ID 49 has any files attached. To do this, we run the following query:

{ files (fileable_type:TicketReply fileable_id:49) { entities { id filename } } }

The response back indicates a file ID of 418 with the associated filename of "Wireless Landlord from.pdf".

{"data":{"files":{"entities":[{"id":"418","filename":"Wireless Landlord form.pdf"}]}}}

With this information, we can then use the following cURL command:

BEARER_TOKEN='ey...'
FILE_ID=418
curl -o 'Wireless Landlord form.pdf' \
--header "Authorization: Bearer $BEARER_TOKEN" \
https://example.sonar.software/api/files/$FILE_ID

For details on what fileable_type and fileable_id are, see the How to Upload Files section.

How did we do?

Controlling Your Landing Page: Personal Preferences

Getting Your Data into Sonar

Contact