Not every caller is your app. A script, a CI job or a payment provider speaks plain HTTP. In this chapter, anyone with a token can post an announcement into the chat with curl.
The backend#
Add type Routes to the import, and export routes below setTyping:
TypeScript
import { ApiError, caller, event, files, online, type Routes } from 'arkapi/server'
TypeScript
export const routes: Routes = {
'POST /announce': async (req) => {
const token = process.env.ANNOUNCE_TOKEN
if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) {
throw new ApiError('UNAUTHORIZED', 'Wrong token')
}
save('announcement', await req.text(), null)
return new Response('ok')
},
}
- Keys are
METHOD /path; a path like/items/:idpassesidin a secondparamsargument. The handler gets a standardRequestand returns aResponse. - The URL is the backend's address plus
/http, so this one ishttp://localhost:3000/http/announcefor now. - The message is saved with the device
announcement, which has no row inpeople. That is whygetMessagesfalls back to the nameAnnouncement. - A route refreshes live queries like a mutation, so the announcement appears on every screen.
Try it#
The token comes from an environment variable. Stop watch, and start it again with one:
Terminal
ANNOUNCE_TOKEN=pizza bunx arkapi watch
Terminal
curl -X POST http://localhost:3000/http/announce \
-H 'Authorization: Bearer pizza' -d 'Pizza in the kitchen'
The app shows the announcement from "Announcement". With a wrong token the answer is 401 and nothing is saved. On the hosted service you set the token with bunx arkapi env set, in the last chapter.
Next: clean up every hour.