Routzie - documentation

Fetch API in Routzie

Introduction

To communicate between services (or even within your own services hosted on Routzie), use the fetch function. This function allows you to easily send HTTP requests and automatically handles various data types for both input and output.

Automatic data conversion

Fetch automatically detects the data type:

  • If the request body is a BlobReference, it will be sent as a blob with the correct MIME type.
  • If the body is an object, it will be sent as JSON.
  • You can also send plain text or FormData.

The same logic applies to the response:

  • If the response contains a blob, response.body will be a BlobReference.
  • If the response contains JSON, response.body will be an object.
  • If the response contains text, response.body will be a string.

Usage examples

1. Download an image and return it to the client

route('GET', 'download-image', async function downloadImage(req: ProcessedRequest) { const result = await fetch(req.context, 'https://picsum.photos/200/300') if (result.body instanceof BlobReference) { return new RouteResult(result.body, 200) } return new RouteResult('Unable to resolve image', 500) })

2. Send JSON data to another machine

route('POST', 'send-data', async function sendData(req: ProcessedRequest) { const payload = { name: 'Test', value: 42 } const result = await fetch(req.context, 'http://otherMachine/api/receive', { method: 'POST', body: payload }) if (typeof result.body === 'object') { return new RouteResult(result.body, 200) } return new RouteResult('Failed to send data', 500) })

3. Send a file as a blob

route('POST', 'upload-file', async function uploadFile(req: ProcessedRequest) { const fileBlob = req.body.file // assuming BlobReference const result = await fetch(req.context, 'http://localhost/storage/upload', { method: 'POST', body: fileBlob }) if (result.body instanceof BlobReference) { return new RouteResult('File uploaded', 200) } return new RouteResult('Upload failed', 500) })

4. Send FormData

route('POST', 'submit-form', async function submitForm(req: ProcessedRequest) { const form = new FormData() form.append('username', 'user1') form.append('file', req.body.file) const result = await fetch(req.context, 'http://localhost/form', { method: 'POST', body: form }) return new RouteResult(result.body, 200) })

Notes

  • Always check the type of result.body according to the expected output.
  • Use BlobReference for binary data.
  • Use objects for JSON data.
  • Use string for text responses.

© 2025 Routzie Routzie.com