Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/%22https:/unpkg.com/react@18/umd/react.development.js/%7Bimport.meta.url.replace(/%22esm.town/%22,?q=api&page=1&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=api

Returns an array of strings in format "username" or "username/projectName"

Found 25402 results for "api"(1379ms)

vtEditorFilesAGENTS.md10 matches

@jrmann100•Updated 1 hour ago
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
24
25- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176
177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225
226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248 });
249 ```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252 ```ts
285 - For files in the project, use `readFile` helpers
286
2875. **API Design:**
288 - `fetch` handler is the entry point for HTTP vals
289 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
9// Simple test endpoint
10app.get("/test", async (c) => {
11 return c.json({ message: "API routes working", timestamp: new Date().toISOString() });
12});
13
120 const { cleanupStaleViewingSessions } = await import("../../controllers/viewing.controller.ts");
121
122 console.log("🔧 Manual cleanup triggered via API");
123 const result = await cleanupStaleViewingSessions();
124
16
17 const updateStatus = async (viewing: boolean, tabVisible: boolean) => {
18 // Only make API calls if user is authorized
19 if (!isAuthorized) {
20 console.log("User not authorized for viewing analytics on this page");

spotymain.ts2 matches

@skirtowner•Updated 3 hours ago
19 const now = Date.now();
20 if (!cached.accessToken || now >= cached.expiresAt) {
21 const tokenResp = await fetch("https://accounts.spotify.com/api/token", {
22 method: "POST",
23 headers: {
46 let playlists: any[] = [];
47 let nextUrl: string | null =
48 "https://api.spotify.com/v1/me/playlists?limit=50";
49
50 while (nextUrl) {
1# API Routes
2
3JSON API endpoints for frontend/backend communication.
4
5## Separation of Concerns
6
7API routes handle:
8- JSON request/response formatting
9- HTTP status code management
11- Error response standardization
12
13API routes delegate business logic to controllers and return clean JSON responses.
14
15## Endpoints
16
17### GET /api/health
18
19**Purpose**: System health check endpoint
32**HTTP Status**: Always 200
33
34### POST /api/viewing
35
36**Purpose**: Update page viewing status in blob storage for real-time tracking with immediate Notion sync
41 pageId: string, // Notion page UUID
42 viewing: boolean, // true when actively viewing, false when leaving
43 tabVisible: boolean // Page Visibility API state
44}
45```
92```
93
94### GET /api/viewing/:id
95
96**Purpose**: Get current viewing status for a page
125**Error Responses**: Same pattern as other endpoints
126
127### GET /api/viewing/:id/stats
128
129**Purpose**: Get viewing analytics/statistics for a page
148```
149
150### GET /api/demo/:id/properties
151
152**Purpose**: Get Notion page properties (filtered for UI consumption)
198{
199 error: "Failed to fetch page data",
200 details: "Notion API error message"
201}
202```
203
204### GET /api/demo/:id
205
206**Purpose**: Get complete Notion page with content blocks
251## Error Handling Pattern
252
253All API routes follow consistent error handling:
254
255```typescript
269## Data Filtering
270
271API routes return filtered data for UI consumption:
272- **Button properties removed**: Notion button properties are filtered out to prevent UI confusion
273- **Raw Notion format**: Other properties maintain their original Notion API structure
274- **Complete hierarchy**: Block content includes full nested structure with children
275
278```bash
279# Get page properties only
280curl https://your-val.web.val.run/api/demo/abc123/properties
281
282# Get complete page with content
283curl https://your-val.web.val.run/api/demo/abc123
284
285# Health check
286curl https://your-val.web.val.run/api/health
287```
67
68**Session Tracking:**
69- Uses `sendBeacon` API for reliable session ending during page unload
70- Falls back to synchronous fetch if sendBeacon fails
71- Handles both normal component unmount and browser tab closure

eventsCalendarserver.ts6 matches

@roop•Updated 5 hours ago
13
14import { Hono } from "npm:hono@4";
15import { SSEStreamingApi, stream, streamSSE } from "npm:hono@4/streaming";
16import { html, raw } from "npm:hono@4/html";
17import process from "node:process";
27 return streamSSE(c, async (stream) => {
28 // validate token
29 const apiToken = c.req.query("token");
30 if (apiToken !== process.env.API_TOKEN) {
31 await fail(stream, "Unauthorized");
32 return stream.close();
209});
210
211function update(stream: SSEStreamingApi, payload: any) {
212 return stream.writeSSE({
213 event: "update",
220
221function complete(
222 stream: SSEStreamingApi,
223 state: "success" | "error",
224) {
233
234function fail(
235 stream: SSEStreamingApi,
236 message?: string,
237) {

eventsCalendarlogs.tsx1 match

@roop•Updated 5 hours ago
20export const dashboard = async (req) => {
21 const token = new URL(req.url).searchParams.get("token");
22 if (token !== process.env.API_TOKEN) {
23 return new Response("Token required to view logs", { status: 403 });
24 }

TopTenVideosREADME.md2 matches

@pmapower•Updated 6 hours ago
80```
81https://yoursite.com/custom-header.html
82https://api.yoursite.com/generate-header
83https://cdn.example.com/headers/analysis.html
84```
146- **Safe External Links**: `noopener noreferrer` attributes
147- **Input Validation**: URL validation for all inputs
148- **XSS Protection**: Proper HTML escaping
149- **Error Boundaries**: Graceful error handling
150

TopTenVideosindex.html2 matches

@pmapower•Updated 6 hours ago
674 });
675
676 // Here you could make an API call to your backend
677 console.log('Selected niche data:', {
678 niche,
767 `;
768
769 // Sample video data (you can replace this with real API data)
770 const sampleVideos = [
771 {

PixelPixelApiMonitor1 file match

@selfire1•Updated 8 hours ago
Regularly polls the API and messages on an error.

weatherApp1 file match

@dcm31•Updated 14 hours ago
A simple weather app with dropdown cities using Open-Meteo API
fapian
<("<) <(")> (>")>
Kapil01