HTTP functions
Serve HTTP endpoints from functions, with routing, CORS, authentication, authorization and per-IP rate limiting.
The http trigger turns a handler into an HTTP endpoint under /fn-execute:
https://api.example.com/api/fn-execute/<path>Options
| Option | Default | Description |
|---|---|---|
method | Get | Get, Post, Put, Patch, Delete, Head or All. |
path | / | Route path. Supports parameters such as /books/:id. |
preflight | true | Answer CORS preflight (OPTIONS) requests for this route using the API's CORS settings. |
authenticate | [] | Strategies allowed to call the route: any of IDENTITY, APIKEY, USER. Empty means public. |
authorize | false | Also check the caller's policies. Requires at least one authenticate strategy. |
rateLimit | {limit, ttl}: at most limit requests per IP within ttl milliseconds. |
triggers:
getBook:
type: http
active: true
options:
method: Get
path: /books/:id
authenticate: [USER, APIKEY]
rateLimit:
limit: 60
ttl: 60000The request
export function getBook(req, res) {
req.method; // "GET"
req.path; // "/books/42"
req.params.id; // "42"
req.query.lang; // "en"
req.headers.get("user-agent"); // headers are a Map with lower-case keys
req.get("authorization"); // shortcut for headers.get
req.cookies.get("session"); // cookies are a Map
req.body; // parsed from JSON or form bodies
req.ip; // client address
}The response
Return a value to send it. Objects and arrays become JSON, strings become text/html, and Buffers are sent as application/octet-stream:
export default async function (req) {
return {ok: true};
}Use res for status codes, headers and streaming:
export async function createBook(req, res) {
if (!req.body?.title) {
return res.status(400).send({message: "title is required"});
}
const book = await saveBook(req.body);
res.headers.set("Location", `/books/${book._id}`);
return res.status(201).send(book);
}| Method | Description |
|---|---|
res.status(code, message?) | Set the status code. Chainable. |
res.send(body) | Send a body and end the response. |
res.json(body) | Send a JSON body and end the response. |
res.headers.set(name, value), res.headers.append(name, value) | Set response headers before sending. |
res.writeHead(status, message?, headers?) | Start a streamed response. |
res.write(chunk, encoding?) | Write a chunk. |
res.end(chunk?, encoding?) | Finish the response. |
When the handler throws or its promise rejects before a response is sent, the client receives 500:
{"statusCode": 500, "error": "Internal Server Error", "message": "Error: database unreachable"}Streaming
export async function events(req, res) {
await res.writeHead(200, "OK", {"Content-Type": "text/event-stream", "Cache-Control": "no-cache"});
for (let i = 1; i <= 3; i++) {
await res.write(`data: tick ${i}\n\n`);
await new Promise(resolve => setTimeout(resolve, 1000));
}
await res.end();
}Authentication and authorization
With authenticate, Spica verifies the Authorization header before the function runs and rejects invalid callers with 401. Your handler can then trust the header and read the caller from it, for example with Identity.verifyToken or Auth.verifyToken.
With authorize: true, the caller's policies are checked as well. Write policies that allow the function's route to control who may call it.
options:
method: Post
path: /orders
authenticate: [USER]
authorize: trueCORS
Function routes use the API's CORS settings (--cors-allowed-origins, --cors-allowed-methods, --cors-allowed-headers, --cors-allow-credentials). Keep preflight: true for routes called from browsers.
Rate limiting
rateLimit counts requests per client IP. When the limit is reached, Spica answers 429 Too Many Requests without running the function. Behind a proxy, make sure --trust-proxy is set so that Spica sees the real client IP.
Calling a function from a client
Use plain fetch:
const response = await fetch("https://api.example.com/api/fn-execute/books/42", {
headers: {Authorization: `USER ${token}`}
});
const book = await response.json();Or generate a typed client for every HTTP function with spica function orm.
Tips
- Validate
req.bodyyourself. Function bodies aren't validated against a schema. - Return early with
res.status(...).send(...)for error cases, so the response is never sent twice. - Keep long work out of the request: write a job to a bucket and process it with a bucket trigger or a schedule.