Upload files with the API
The upload API lets you upload files to your Sirv account. Two upload methods are available:
- Standard uploads - for most cases
- tus.io multipart uploads - for very large files, faster uploads or less stable connections
Standard uploads
Files should be uploaded one at a time to the endpoint https://api.sirv.com/v2/files/upload.
Your request must include the following parameters:
- filename - folder path and file name to where the file should be saved in your Sirv account.
- content-type - content-type of the original file being uploaded e.g. image/png. See list of common content types.
- Location of local file being uploaded.
The filename can contain any folder path - if the folder(s) do not already exist, they will be created on Sirv.
The file name itself can be anything - it does not need to match the original file name. We recommend using only safe characters a-z A-Z 0-9 - _ which don't need to be encoded in URLs. This will avoid possible problems with any systems/services that do not properly encode reserved characters.
Depending on the script you use, the filename might be included in a query string after the endpoint URL. As with any query string, special characters should be encoded. The path to where the file is being uploaded should start with a forward slash / which should be encoded as %2F. The following URL would be used to upload the file Example-Image.jpg:
https://api.sirv.com/v2/files/upload?filename=%2FExample-Image.jpg
Your requests must use binary content encoding, not base64.
Example scripts
The REST API upload documentation contains an example payload, JSON schema, response and scripts for 10 popular programming languages:
- cURL upload example | more cURL examples
- Python upload example | more Python examples
- Node.js upload example | more Node.js examples
- JavaScript upload example
- Java upload example | more Java examples
- PHP upload example | more PHP examples
- Ruby upload example
- Swift upload example
- Go upload example
- C# upload example
- jQuery example
Example response
For each upload request, Sirv will return a response containing some useful headers and an empty body. In the headers, you will receive your hourly upload limit, the number of requests remaining and the time when the limit will reset (in 10-digit epoch time):
< HTTP/1.1 200 < date: Fri, 03 Jun 2022 15:21:07 GMT < content-length: 0 < connection: close < x-ratelimit-limit: 2000 < x-ratelimit-remaining: 1999 < x-ratelimit-reset: 1654273267 < x-ratelimit-type: rest:post:files:upload < access-control-allow-origin: * < access-control-expose-headers: * < cache-control: no-cache < server: Sirv.API < strict-transport-security: max-age=31536000
The response also includes CORS headers for access-control-allow-origin and access-control-expose-headers. These indicate to the browser that it should permit the loading of resources from any origin (domain, scheme or port).
How to handle upload errors
A successful upload will return a 200 response. If you receive any other response, your script should retry or take some other action.
We recommend logging each response - this will allow you to build up a history of uploads, which will help you troubleshoot any issue.
These are the possible error responses that your script should handle:
- 401 - The Unauthorized error probably means that your API access token has reached its expiry. If so, get a new token and try again. You can set a bearer token expiry of between 5 seconds and 7 days.
- 403 - The Forbidden error means that you are not permitted to upload a file to the path, for example because a file with the same name already exists at the destination, in a protected folder. Consider saving the file with another name or path.
- 429 - The Too Many Requests error will be returned if you have reached your hourly file upload limit. Your limit and current status is shown on the Usage page of your Sirv account. To handle such an error, pause your upload script and resume your uploads once your hourly limit has refreshed.
- 503 - The Service Unavailable error will be returned if Sirv's upload service is overloaded. If files cannot be uploaded immediately, they join a queue. If the queue becomes too long, new requests won't be added to the queue and a 503 response will be returned. This is a rare occurence that will resolve itself after some time. To handle such an error, we recommend retrying after 15 to 30 minutes.
File size limit
The file size limit for API uploads is 300 MB. If you need to upload larger files, please use Sirv's tus.io multipart upload API or contact the Sirv team to discuss your requirements.
Hourly file upload limit
Your account can upload a large number of files per hour. There is a limit as follows:
- Enterprise plan - 4,000 uploads per hour
- Business plan - 2,000 uploads per hour
- Trial plan - 2,000 uploads per hour
- Free plan - 300 uploads per hour
If you reach your hourly limit, pause uploads until the limit refreshes. If you regularly reach your upload limit, consider using Sirv's tus.io multipart upload API instead.
Troubleshooting
If you receive a 400 error response that the filename "fails to match the UNIX filename pattern", please add a leading slash to the file path. For example, change this:
my-file.jpg
to:
/my-file.jpg
This upload API does not support multipart - files should be uploaded directly as a binary stream. For multipart uploads, please use the tus.io API method described below.
Protect your API key
If you use the upload API to let third parties upload files to your Sirv account, consider how to protect your API credentials. You should keep your client ID and client secret private, without exposing them in your code.
There are 2 ways to allow uploads without exposing your key:
- You could configure your page so that the user uploads files to your backend first. Then your backend can upload the file to your Sirv account.
- Alternatively, you can use the API key on your backend to issue JWT tokens for your web app. This way only the 20 minutes JWT token will be exposed.
tus.io multipart uploads
Instead of the standard upload API, you can use the tus.io upload API. tus.io uploads files by breaking them into smaller chunks, up to 1MB per chunk. This method of uploading has the following benefits over standard API uploads:
- Multipart uploads
- Lower latency, faster upload (to nearest of 24 CDN locations)
- Higher hourly upload limit
- Large maximum file size of 1 GB
Instructions
1. Use your REST API client ID and secret or create a new one.
2. Connect to Sirv and retrieve a token as normal.
3. Send a REST API request to GET /v2/files/tus/locations and you will receive a response containing a list of locations, similar to this:
[ "au_sydney", "br_sao_paulo", "ca_monreal", "de_falkenstein", "fi_helsinki", "fr_paris", "gb_london", "hk_hong_kong", "in_mumbai", "kr_seoul", "nz_christchurch", "sg_singapore", "us_atlanta", "us_buffalo", "us_chicago", "us_dallas", "us_kansas", "us_los_angeles", "us_miami", "us_phoenix", "us_seattle", "us_washington", "za_capetown" ]
4. Send a tus.io upload URL request, with your desired upload location e.g.
GET /v2/files/tus/url?location=us_washington
The response will contain a URL similar to this:
{ "url": "https://sirvcdn-gbr-4.sirv.com:444/upload/eyJhbhoaigGSiuhgkahFFGnX0" }
The upload URL has an expiration of 3600 seconds (1 hour). You can change that by setting expiresIn as a URL parameter. This example sets 7200 seconds:
GET /v2/files/tus/url?location=gb_london&expiresIn=7200
5. Use the URL that you received as the 'endpoint' for a tus.io command or script. Provide your desired filename in the metadata.filename field. Example with JavaScript:
const upload = new tus.Upload(data, { endpoint: "https://sirvcdn-gbr-4.sirv.com:444/upload/eyJhbhoaigGSiuhgkahFFGnX0", retryDelays: [0, 3000, 5000, 10000, 20000], chunkSize: 1024*1024, metadata: { filename: '/my-folder/my-image.jpg' }, onError: function(error) { console.log("Failed because: " + error) }, onProgress: function(bytesUploaded, bytesTotal) { var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2) console.log(bytesUploaded, bytesTotal, percentage + "%") }, onSuccess: function() { console.log("Upload complete %s", upload.url) } })
Delayed upload
With tus.io uploads, your files will be uploaded to your chosen Sirv CDN server (we recommend choosing the nearest server to your location). The low latency of uploading to a server near you means that each upload will complete very quickly. Sirv will then transfer the files onwards to your Sirv account, which means there will be a small delay (typically 1-4 seconds) before the files show in your Sirv account.
Get expert help
If you'd like advice using the file upload API, please contact the Sirv customer success team.