Files API
This documentation is verified against the actual API test suite (test/file.test.js).
Overview
The Files API provides file upload, storage, retrieval, and management capabilities. Files can be uploaded directly from your device or from a remote URL.
Key Features:
- Upload files via multipart/form-data
- Upload files from URL
- File metadata management
- Secure file storage
- File deletion
Upload File
Upload a file to the system.
Endpoint: POST /files
Authentication: Required (Bearer token)
Content-Type: multipart/form-data
Request
Send file as form-data with field name file:
curl -X POST "http://localhost:3000/files" \
-H "Authorization: Bearer YOUR_TOKEN" \
-F "file=@/path/to/your/file.jpg"Response
Success (200 OK):
{
"data": "file-id-here"
}The response contains the file ID which can be used to reference the file in other API calls.
Example with Node.js
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
form.append('file', fs.createReadStream('/path/to/file.jpg'));
const response = await fetch('http://localhost:3000/files', {
method: 'POST',
headers: {
Authorization: 'Bearer YOUR_TOKEN',
...form.getHeaders(),
},
body: form,
});
const data = await response.json();
console.log('File ID:', data.data);Get File Details
Retrieve metadata about a file.
Endpoint: GET /files/:id
Authentication: Required (Bearer token)
URL Parameters
| Parameter | Type | Description |
|---|---|---|
| id | string | File ID returned from upload |
Response
Success (200 OK):
{
"data": {
"id": "file-id",
"filename": "test-image.jpg",
"type": "image/jpeg",
"size": 15234
}
}| Field | Type | Description |
|---|---|---|
| id | string | Unique file identifier |
| filename | string | Original filename |
| type | string | MIME type of the file |
| size | number | File size in bytes |
Error (403 Forbidden):**
When file doesn't exist or has been deleted:
{
"error": {
"message": "File not found or access denied"
}
}Example
curl "http://localhost:3000/files/file-id" \
-H "Authorization: Bearer YOUR_TOKEN"Update File Metadata
Update file information like title and description.
Endpoint: PATCH /files/:id
Authentication: Required (Bearer token)
URL Parameters
| Parameter | Type | Description |
|---|---|---|
| id | string | File ID to update |
Request Body
{
"title": "Updated Test Image",
"description": "This is an updated test image"
}| Field | Type | Required | Description |
|---|---|---|---|
| title | string | No | File title |
| description | string | No | File description |
Response
Success (200 OK):
{
"data": "file-id"
}Example
curl -X PATCH "http://localhost:3000/files/file-id" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "My Photo",
"description": "Vacation photo from 2024"
}'Upload File from URL
Upload a file from a remote URL.
Endpoint: POST /files/upload-from-url
Authentication: Required (Bearer token)
Request Body
{
"url": "https://www.example.com/image.png"
}| Field | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | Public URL of the file to upload |
Response
Success (200 OK):
{
"data": "file-id"
}Example
curl -X POST "http://localhost:3000/files/upload-from-url" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"url": "https://www.gstatic.com/webp/gallery3/1.png"
}'Use Cases
- Import files from external sources
- Copy files from public URLs
- Batch import from web services
- Migrate files from other systems
Delete File
Delete a file from the system.
Endpoint: DELETE /files/:id
Authentication: Required (Bearer token)
URL Parameters
| Parameter | Type | Description |
|---|---|---|
| id | string | File ID to delete |
Response
Success (200 OK):
{
"message": "File deleted successfully"
}Post-Deletion Behavior
After deletion:
- The file is permanently removed from storage
- File metadata is removed from the database
- Attempts to access the file will return 403 Forbidden
- The file ID becomes invalid
Example
curl -X DELETE "http://localhost:3000/files/file-id" \
-H "Authorization: Bearer YOUR_TOKEN"Complete Workflow Example
1. Upload a File
FILE_ID=$(curl -X POST "http://localhost:3000/files" \
-H "Authorization: Bearer YOUR_TOKEN" \
-F "file=@photo.jpg" | jq -r '.data')
echo "Uploaded file ID: $FILE_ID"2. Get File Details
curl "http://localhost:3000/files/$FILE_ID" \
-H "Authorization: Bearer YOUR_TOKEN"3. Update File Metadata
curl -X PATCH "http://localhost:3000/files/$FILE_ID" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Vacation Photo",
"description": "Summer 2024"
}'4. Use File in Other Collections
curl -X POST "http://localhost:3000/items/posts" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "My Post",
"content": "Check out this photo!",
"featuredImage": "'"$FILE_ID"'"
}'5. Delete File (When No Longer Needed)
curl -X DELETE "http://localhost:3000/files/$FILE_ID" \
-H "Authorization: Bearer YOUR_TOKEN"Get Asset
Retrieve a file with optional transformations. This endpoint serves all file types - images, documents, videos, audio, and more.
Endpoint: GET /assets/:id
Authentication: Required (Bearer token) - unless file is public
URL Parameters
| Parameter | Type | Description |
|---|---|---|
| id | string | File ID to retrieve |
Query Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
download | boolean | Force browser to download the file instead of displaying inline | download=true |
width | number | (Images only) Target width in pixels | width=300 |
height | number | (Images only) Target height in pixels | height=200 |
fit | string | (Images only) Resize fit mode (see options below) | fit=cover |
quality | number | (Images only) JPEG quality (1-100) | quality=80 |
withoutEnlargement | boolean | (Images only) Prevent upscaling images smaller than target | withoutEnlargement=true |
File Type Behavior
Images (JPEG, PNG, GIF, WebP, etc.): Transformation parameters are applied and transformed images are returned as JPEG.
Non-image files (PDF, Video, Audio, Documents, etc.): Served as-is without any transformation. Transformation parameters are ignored.
Fit Options (Images Only)
| Value | Description |
|---|---|
cover | (Default) Crop to cover the target dimensions, maintaining aspect ratio |
contain | Fit inside target dimensions, maintaining aspect ratio (may have letterboxing) |
fill | Stretch to fill target dimensions exactly (may distort image) |
inside | Preserve aspect ratio, resize to be as large as possible within target |
outside | Preserve aspect ratio, resize to be as small as possible while covering target |
Response
Returns the file binary data with appropriate Content-Type header.
Headers for images:
Content-Type: image/jpeg
Content-Length: 45234Headers for other files (PDF example):
Content-Type: application/pdf
Content-Length: 123456Headers when download=true:
Content-Type: application/pdf
Content-Disposition: attachment; filename="document.pdf"; filename*=UTF-8''document.pdfExamples
Basic File Retrieval
# Get original file (no transformations)
curl "http://localhost:3000/assets/file-id" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o file.extDownload File as Attachment
# Force download with original filename
curl "http://localhost:3000/assets/file-id?download=true" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o document.pdfRetrieve Non-Image Files
# Get a PDF document
curl "http://localhost:3000/assets/pdf-file-id" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o document.pdf
# Get a video file
curl "http://localhost:3000/assets/video-file-id" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o video.mp4Resize Image to Specific Width
# Resize to 300px width, height auto-calculated
curl "http://localhost:3000/assets/file-id?width=300" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o thumbnail.jpgResize Image with Both Dimensions
# Resize to 300x200 with cover fit
curl "http://localhost:3000/assets/file-id?width=300&height=200&fit=cover" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o cropped.jpgThumbnail with Quality Optimization
# Create optimized thumbnail (smaller file size)
curl "http://localhost:3000/assets/file-id?width=150&height=150&fit=cover&quality=70" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o thumb.jpgPrevent Upscaling Small Images
# Won't enlarge images smaller than 800px
curl "http://localhost:3000/assets/file-id?width=800&withoutEnlargement=true" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o safe-resize.jpgContain Fit (No Cropping)
# Fit within 400x400 box without cropping
curl "http://localhost:3000/assets/file-id?width=400&height=400&fit=contain" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o contained.jpgUse Cases
Responsive Images
Generate multiple sizes for responsive design:
<picture>
<source srcset="http://localhost:3000/assets/file-id?width=1200" media="(min-width: 1200px)" />
<source srcset="http://localhost:3000/assets/file-id?width=800" media="(min-width: 800px)" />
<source srcset="http://localhost:3000/assets/file-id?width=400" media="(min-width: 400px)" />
<img src="http://localhost:3000/assets/file-id?width=400" alt="Responsive image" />
</picture>Thumbnail Gallery
// Generate thumbnails for gallery
const thumbnailUrl = `${baseUrl}/assets/${fileId}?width=200&height=200&fit=cover&quality=75`;
// Full-size preview on click
const fullSizeUrl = `${baseUrl}/assets/${fileId}?width=1920&quality=90`;Avatar Images
// Consistent avatar sizing
const avatarUrl = `${baseUrl}/assets/${userId}?width=100&height=100&fit=cover`;Optimized Loading
// Low-quality placeholder (blur-up technique)
const placeholder = `${baseUrl}/assets/${fileId}?width=20&quality=30`;
// Full quality image
const fullImage = `${baseUrl}/assets/${fileId}?width=800&quality=85`;File Downloads
// Provide download link for a PDF
const downloadUrl = `${baseUrl}/assets/${pdfFileId}?download=true`;
// Force download for any file type
const downloadLink = document.createElement('a');
downloadLink.href = `${baseUrl}/assets/${fileId}?download=true`;
downloadLink.click();Caching
Transformed images are automatically cached in the same storage adapter as the original file:
- Processed images are stored alongside original files (LOCAL or S3)
- Same transformation parameters return cached version instantly
- Cache filenames include a hash of transform parameters for uniqueness
Notes
- All File Types Supported: Images, PDFs, videos, audio, documents, and any other file type can be served through this endpoint
- Image Transformations: Only applicable to image files (JPEG, PNG, GIF, WebP, etc.)
- Non-Image Files: Served as-is without any transformation
- Download Mode: Use
download=trueto force the browser to download the file with its original filename instead of displaying inline - Original Preserved: Original files are never modified; image transformations create new cached versions
- Image Format: Transformed images are returned as JPEG regardless of original format
- Video Streaming: Video files support HTTP range requests for streaming playback
- S3 Support: Works with both local storage and S3-stored files
File Storage
Files are stored using the configured storage provider (local filesystem or cloud storage like AWS S3). The storage location is determined by environment variables:
File Size Limit
The maximum file upload size is configurable via the MAX_UPLOAD_FILE_SIZE environment variable (in megabytes):
# Default: 50MB
MAX_UPLOAD_FILE_SIZE=50
# 100MB
MAX_UPLOAD_FILE_SIZE=100
# 500MB
MAX_UPLOAD_FILE_SIZE=500
# 1GB
MAX_UPLOAD_FILE_SIZE=1024Storage Configuration
For local storage:
STORAGE_TYPE=local
STORAGE_LOCAL_ROOT=/path/to/storageOr for S3:
STORAGE_TYPE=s3
STORAGE_S3_BUCKET=my-bucket
STORAGE_S3_REGION=us-east-1
STORAGE_S3_ACCESS_KEY=your-access-key
STORAGE_S3_SECRET_KEY=your-secret-keySupported File Types
The system supports all file types. Common examples:
Images:
- JPEG (.jpg, .jpeg)
- PNG (.png)
- GIF (.gif)
- WebP (.webp)
- SVG (.svg)
Documents:
- PDF (.pdf)
- Word (.doc, .docx)
- Excel (.xls, .xlsx)
- PowerPoint (.ppt, .pptx)
Media:
- Video (.mp4, .mov, .avi)
- Audio (.mp3, .wav, .ogg)
Archives:
- ZIP (.zip)
- RAR (.rar)
- TAR (.tar, .gz)
Best Practices
File Organization
- Use Meaningful Titles: Set descriptive titles when uploading
- Add Descriptions: Document what each file contains
- Clean Up: Delete unused files to save storage space
- Reference Files: Store file IDs in your collection items
Security
- All file operations require authentication
- File access is controlled by permissions
- Deleted files are permanently removed
- Use secure HTTPS for file uploads
Performance
- Upload files directly when possible (faster than URL upload)
- Consider file size limits based on your infrastructure
- Use appropriate file formats (WebP for images, compressed videos, etc.)
Related Documentation
Data Integration
- Item Routes - Reference files in your data collections
- Schema Reference Guide - UUID fields for file references
Access Control
- Authentication Routes - File upload authentication
- Permission Routes - File access control
Storage Configuration
- Additional Features - Storage services (local, S3) configuration
- Settings Routes - Storage settings management
- Deployment Guide - Production storage setup
Integration
- Integration Guide - Client-side file uploads
- API Routes Reference - Complete endpoint listing