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/$2?q=api&page=20&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 17843 results for "api"(2393ms)

TownieREADME.md12 matches

@KhadijahAleeyuAUpdated 1 day ago
1# Usage Dashboard
2
3A dashboard for monitoring API usage and inference calls.
4
5## Features
20 index.ts # Main entry point and routing
21 auth.ts # Authentication logic
22 /api/
23 index.ts # API request handler
24 requests.ts # API endpoints for requests data
25 inference-calls.ts # API endpoints for inference calls
26 user-summary.ts # API endpoints for user summary data
27 /views/
28 layout.ts # Common layout template
54 - Links back to the associated request
55
56### API Endpoints
57
58- `/api/requests` - Get paginated requests
59- `/api/requests?usage_id=123` - Get a specific request
60- `/api/inference-calls` - Get paginated inference calls
61- `/api/inference-calls?usage_id=123` - Get inference calls for a specific request
62- `/api/user-summary` - Get user summary data
63
64## Debugging

Towniequeries.tsx5 matches

@KhadijahAleeyuAUpdated 1 day ago
24 user_id = ?
25 AND timestamp > ?
26 AND our_api_token = 1
27 `,
28 [userId, new Date().getTime() - 24 * 60 * 60 * 1000],
113 branch_id,
114 model,
115 our_api_token,
116 num_images,
117}: {
120 branch_id: string;
121 model: string;
122 our_api_token: boolean;
123 num_images: number;
124}) {
132 branch_id,
133 model,
134 our_api_token,
135 num_images
136 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
143 branch_id,
144 model,
145 our_api_token ? 1 : 0,
146 num_images,
147 ],

Townieindex.ts3 matches

@KhadijahAleeyuAUpdated 1 day ago
41);
42
43// token middleware for API requests
44app.all("/api/*", async (c, next) => {
45 const sessionCookie = getCookie(c, "_session");
46 if (!sessionCookie) {
52});
53
54app.route("/api", backend);
55
56app.get("/frontend/*", (c) => {

Townieindex.ts7 matches

@KhadijahAleeyuAUpdated 1 day ago
1import { basicAuthMiddleware } from "./auth.ts";
2import { handleApiRequest } from "./api/index.ts";
3import { getRequests } from "./api/requests.ts";
4import { getUserSummary } from "./api/user-summary.ts";
5import { getInferenceCalls } from "./api/inference-calls.ts";
6import { renderDashboard } from "./views/dashboard.ts";
7import { renderRequests } from "./views/requests.ts";
22 const path = url.pathname;
23
24 // Handle API requests
25 if (path.startsWith("/api/")) {
26 return handleApiRequest(req);
27 }
28

Townieindex.ts5 matches

@KhadijahAleeyuAUpdated 1 day ago
4
5/**
6 * Handle API requests
7 */
8export async function handleApiRequest(req: Request): Promise<Response> {
9 const url = new URL(req.url);
10 const path = url.pathname.replace("/api/", "");
11
12 try {
13 // Route to the appropriate API handler
14 if (path === "requests") {
15 const usageId = url.searchParams.get("usage_id");
59 }
60 } catch (error) {
61 console.error("API error:", error);
62 return new Response(JSON.stringify({ error: error.message }), {
63 status: 500,

TownieHome.tsx5 matches

@KhadijahAleeyuAUpdated 1 day ago
32 <ol>
33 <li>
34 Login with your Val Town API token (with projects:read, projects:write, user:read permissions)
35 </li>
36 <li>Select a project to work on</li>
70 </div>
71 <h3>Cost Tracking</h3>
72 <p>See estimated API usage costs for each interaction</p>
73 </div>
74 </section>
79 <ul>
80 <li>React frontend with TypeScript</li>
81 <li>Hono API server backend</li>
82 <li>Web Audio API for sound notifications</li>
83 <li>AI SDK for Claude integration</li>
84 </ul>
85 <p>
86 The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
87 project files directly.
88 </p>

Townie.cursorrules10 matches

@KhadijahAleeyuAUpdated 1 day 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`

ChatREADME.md7 matches

@c15rUpdated 1 day ago
1# Anthropic Streaming Chat with MCP
2
3A mobile-optimized single page chat application that uses the Anthropic Messages API with **real-time streaming** and MCP (Model Context Protocol) server support.
4
5Source: https://www.val.town/x/c15r/Chat
16- **⏹️ Stream control** - Stop streaming at any time with the stop button
17- Full-screen mobile-optimized chat interface
18- Direct client-side Anthropic API integration with server-side streaming proxy
19- **Model selection** - Choose between different Claude models (3.5 Sonnet, 3.5 Haiku, 3 Opus, etc.) without clearing chat history
20- Configurable MCP servers with localStorage persistence
64
65The app stores configuration and chat history in localStorage:
66- `anthropic_api_key`: Your Anthropic API key
67- `selected_model`: The chosen Claude model (defaults to claude-3-5-sonnet-20241022)
68- `mcp_servers`: Array of configured MCP servers
69- `chat_messages`: Complete chat history (persists between page loads)
70
71## API Endpoints
72
73- `GET /` - Main application (serves frontend)
80
811. Open the app at the provided URL
822. Click "Settings" in the footer to configure your Anthropic API key and select your preferred Claude model
833. Add/remove/toggle MCP servers as needed
844. Use the "Test" button next to each MCP server to verify connectivity (shows ✅ for success, ❌ for errors)
107- **Auto-scroll**: Messages automatically scroll to bottom during streaming
108- **Auto-resize**: Input field grows with content
109- **Error Handling**: Clear error messages for API issues with stream recovery
110- **Loading States**: Visual feedback during API calls and streaming
111- **Structured Responses**: MCP tool use and results are displayed in organized, collapsible sections
112- **Clean Interface**: Maximized chat area with no header, footer contains all controls

ChatuseAnthropicStream.tsx7 matches

@c15rUpdated 1 day ago
86 /* Anthropic SDK instance – memoised so we don't recreate each render */
87 const anthropic = React.useMemo(() => {
88 if (!config.anthropicApiKey) return null;
89 return new Anthropic({
90 dangerouslyAllowBrowser: true,
91 apiKey: config.anthropicApiKey,
92 baseURL: "https://api.anthropic.com", // explicit so it works with CORS pre‑flights
93 defaultHeaders: {
94 "anthropic-version": "2023-06-01",
95 // Allow calling the API directly from the browser – you accept the risk!
96 "anthropic-dangerous-direct-browser-access": "true",
97 },
98 });
99 }, [config.anthropicApiKey]);
100
101 /* Abort helper */
110 const send = React.useCallback(
111 async (history: Message[], userText: string): Promise<AssistantMsg> => {
112 if (!anthropic) throw new Error("API key missing");
113 if (status !== "idle") throw new Error("Stream already in progress");
114
135 })) as AsyncIterable<MessageStreamEvent>;
136 } catch (err: any) {
137 console.error("Failed to call Anthropic API", err);
138 throw err;
139 }

TownieuseUser.tsx1 match

@claudiaowusuUpdated 1 day ago
1import { useState, useEffect } from "react";
2
3const USER_ENDPOINT = "/api/user";
4
5export function useUser() {

dailyQuoteAPI

@SoukyUpdated 21 hours ago

HTTP

@NcharityUpdated 23 hours ago
Daily Quote API
Kapil01
apiv1