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
List Files
Retrieve a list of files with optional filtering and pagination.
Endpoint: GET /files
Authentication: Required (Bearer token)
Query Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
| fields | string | Select specific fields to return | ?fields=id,filename,type,size |
| filter | object | Filter files by field values | ?filter={"type":"image/jpeg"} |
| sort | object | Sort results by field | ?sort={"createdAt":"desc"} |
| limit | number | Maximum number of files to return | ?limit=20 |
| page | number | Page number for pagination | ?page=1 |
| search | string | Search term for filename | ?search=profile |
Response
Success (200 OK):
{
"data": [
{
"id": "file-id-1",
"filename": "image1.jpg",
"type": "image/jpeg",
"size": 15234,
"createdAt": "2024-01-15T10:30:00.000Z"
},
{
"id": "file-id-2",
"filename": "document.pdf",
"type": "application/pdf",
"size": 102400,
"createdAt": "2024-01-14T08:15:00.000Z"
}
],
"meta": {
"total": 50,
"page": 1,
"limit": 20,
"totalPages": 3
}
}Example
# List all files
curl "http://localhost:3000/files" \
-H "Authorization: Bearer YOUR_TOKEN"
# List with pagination and filter
curl "http://localhost:3000/files?limit=10&page=1&filter=%7B%22type%22%3A%22image%2Fjpeg%22%7D" \
-H "Authorization: Bearer YOUR_TOKEN"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 Single File
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
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 Image Transformations
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) Output quality (1-100) | quality=80 |
format | string | (Images only) Output format: jpeg, png, webp, avif | format=webp |
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. The output format matches the format parameter (defaults to jpeg). Transparency is preserved for webp and png output; for jpeg output, transparent areas are composited over a white background.
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 matches the requested format):
# Default (JPEG)
Content-Type: image/jpeg
Content-Length: 45234
# With ?format=webp
Content-Type: image/webp
Content-Length: 31200
# With ?format=png
Content-Type: image/png
Content-Length: 78900Headers 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.jpgConvert to WebP
# Convert image to WebP format
curl "http://localhost:3000/assets/file-id?format=webp&quality=85" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o image.webpConvert to PNG (with transparency)
# Convert image to PNG, preserving transparency
curl "http://localhost:3000/assets/file-id?format=png" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o image.pngConvert to AVIF
# Convert image to AVIF for maximum compression
curl "http://localhost:3000/assets/file-id?format=avif&quality=80" \
-H "Authorization: Bearer YOUR_TOKEN" \
-o image.avifUse Cases
Responsive Images
Generate multiple sizes for responsive design:
<picture>
<!-- Serve WebP to browsers that support it -->
<source
type="image/webp"
srcset="http://localhost:3000/assets/file-id?width=1200&format=webp"
media="(min-width: 1200px)"
/>
<source
type="image/webp"
srcset="http://localhost:3000/assets/file-id?width=800&format=webp"
media="(min-width: 800px)"
/>
<source
type="image/webp"
srcset="http://localhost:3000/assets/file-id?width=400&format=webp"
media="(min-width: 400px)"
/>
<!-- Fallback JPEG for older browsers -->
<img src="http://localhost:3000/assets/file-id?width=400" alt="Responsive image" />
</picture>Thumbnail Gallery
// Generate WebP thumbnails for gallery (modern format, smaller file size)
const thumbnailUrl = `${baseUrl}/assets/${fileId}?width=200&height=200&fit=cover&quality=75&format=webp`;
// Full-size preview on click
const fullSizeUrl = `${baseUrl}/assets/${fileId}?width=1920&quality=90&format=webp`;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
- Output Format: The output format matches the
formatquery parameter (jpeg,webp,png,avif). Defaults tojpegwhen not specified - Transparency:
webpandpngoutput preserve alpha transparency.jpegoutput composites transparent areas over a white background - 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_SERVICES_ENABLED=LOCAL
STORAGE_DEFAULT_SERVICE=LOCAL
LOCAL_STORAGE_DRIVER=LOCAL
LOCAL_STORAGE_PATH=./uploadsOr for S3:
STORAGE_SERVICES_ENABLED=S3
STORAGE_DEFAULT_SERVICE=S3
S3_STORAGE_DRIVER=S3
S3_STORAGE_BUCKET=my-bucket
S3_STORAGE_REGION=us-east-1
S3_STORAGE_ACCESS_KEY_ID=your-access-key
S3_STORAGE_SECRET_ACCESS_KEY=your-secret-key
S3_STORAGE_ENDPOINT=s3.amazonaws.comSupported 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