BaasixBaasix
Guides

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

ParameterTypeDescriptionExample
fieldsstringSelect specific fields to return?fields=id,filename,type,size
filterobjectFilter files by field values?filter={"type":"image/jpeg"}
sortobjectSort results by field?sort={"createdAt":"desc"}
limitnumberMaximum number of files to return?limit=20
pagenumberPage number for pagination?page=1
searchstringSearch 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

ParameterTypeDescription
idstringFile ID returned from upload

Response

Success (200 OK):

{
  "data": {
    "id": "file-id",
    "filename": "test-image.jpg",
    "type": "image/jpeg",
    "size": 15234
  }
}
FieldTypeDescription
idstringUnique file identifier
filenamestringOriginal filename
typestringMIME type of the file
sizenumberFile 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

ParameterTypeDescription
idstringFile ID to update

Request Body

{
  "title": "Updated Test Image",
  "description": "This is an updated test image"
}
FieldTypeRequiredDescription
titlestringNoFile title
descriptionstringNoFile 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"
}
FieldTypeRequiredDescription
urlstringYesPublic 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

ParameterTypeDescription
idstringFile 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

ParameterTypeDescription
idstringFile ID to retrieve

Query Parameters

ParameterTypeDescriptionExample
downloadbooleanForce browser to download the file instead of displaying inlinedownload=true
widthnumber(Images only) Target width in pixelswidth=300
heightnumber(Images only) Target height in pixelsheight=200
fitstring(Images only) Resize fit mode (see options below)fit=cover
qualitynumber(Images only) Output quality (1-100)quality=80
formatstring(Images only) Output format: jpeg, png, webp, avifformat=webp
withoutEnlargementboolean(Images only) Prevent upscaling images smaller than targetwithoutEnlargement=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)

ValueDescription
cover(Default) Crop to cover the target dimensions, maintaining aspect ratio
containFit inside target dimensions, maintaining aspect ratio (may have letterboxing)
fillStretch to fill target dimensions exactly (may distort image)
insidePreserve aspect ratio, resize to be as large as possible within target
outsidePreserve 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: 78900

Headers for other files (PDF example):

Content-Type: application/pdf
Content-Length: 123456

Headers when download=true:

Content-Type: application/pdf
Content-Disposition: attachment; filename="document.pdf"; filename*=UTF-8''document.pdf

Examples

Basic File Retrieval

# Get original file (no transformations)
curl "http://localhost:3000/assets/file-id" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -o file.ext

Download File as Attachment

# Force download with original filename
curl "http://localhost:3000/assets/file-id?download=true" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -o document.pdf

Retrieve 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.mp4

Resize 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.jpg

Resize 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.jpg

Thumbnail 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.jpg

Prevent 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.jpg

Contain 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.jpg

Convert 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.webp

Convert 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.png

Convert 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.avif

Use 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>
// 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=true to 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 format query parameter (jpeg, webp, png, avif). Defaults to jpeg when not specified
  • Transparency: webp and png output preserve alpha transparency. jpeg output 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=1024

Storage Configuration

For local storage:

STORAGE_SERVICES_ENABLED=LOCAL
STORAGE_DEFAULT_SERVICE=LOCAL
LOCAL_STORAGE_DRIVER=LOCAL
LOCAL_STORAGE_PATH=./uploads

Or 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.com

Supported 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

  1. Use Meaningful Titles: Set descriptive titles when uploading
  2. Add Descriptions: Document what each file contains
  3. Clean Up: Delete unused files to save storage space
  4. 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.)

Data Integration

Access Control

Storage Configuration

Integration

On this page