Working With Files in the Ninox API

By Adam Davidson, Director of Product Development

This Article will be part of a series of articles which will explain how to use the Ninox API to work with files that are attached to records in Ninox.

There may come a situation where you need to deal with file attachments via the API rather than using Ninox functions. To demonstrate how a file upload is done with the API, we will create a file selector and uploader in Javascript which will be placed in a formula function in Ninox.

Place the following code in a formula function in Ninox:

				
					html(" <script>function uploadFile(){let file=event.target.files[0];let formData=new FormData();formData.append('file',file);let url='https://api.ninox.com/v1/teams/" + teamId() + "/databases/" + databaseId() + "/tables/" + tableId(this) + "/records/" + Id + "/files';fetch(url,{method:'POST',body:formData,headers:{'Authorization':'Bearer " + apiKey() + "'}})}</script> <form>
	<input type=file onchange='uploadFile()'></input>
</form>
")
				
			

The code above creates a form with a file selector button. When a file is selected , the function “uploadFile()” sends the file to the Ninox API. The function is called in the onchange function for the input element, so the upload will occur as soon as the file is selected. The code will attach the file to the current record.

Note that we have used the global function apiKey() to access the API key here for security. You will have to replace this with your own API key if you use it in your database.

The body of the HTTP request being sent to Ninox needs to be in a particular format when sending files. The above code uses the browser’s built in FormData() object to make sure that the call is made in the correct way. When a FormData object is passed into the body of a fetch() request, a few headers are added to the request which are necessary for the form to be sent correctly.

In this case it is just as easy to go to the attachments and upload the file there. This method will work well when you would like a central location from which you would like to upload files, or you would like to create a custom file upload button.  Next time we will look at more applications of the files API.