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/image-url.jpg%20%22Image%20title%22?q=api&page=6&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 19724 results for "api"(4929ms)

Townieindex.ts9 matches

@ianmenethil•Updated 8 hours ago
1import { Hono } from "https://esm.sh/hono@3.11.7";
2import { getCreditAdditions } from "./api/credit-additions.ts";
3import { handleApiRequest } from "./api/index.ts";
4import { getInferenceCalls } from "./api/inference-calls.ts";
5import {
6 getInferenceCallsForRequest,
8 getRequestById,
9 getRequests,
10} from "./api/requests.ts";
11import { getUserSummary } from "./api/user-summary.ts";
12import { getValSummary } from "./api/val-summary.ts";
13import { basicAuthMiddleware } from "./auth.ts";
14import { renderCreditAdditions } from "./views/credit-additions.ts";
31});
32
33// API routes
34app.all("/api/*", async (c) => {
35 return handleApiRequest(c.req.raw);
36});
37

Townieindex.ts5 matches

@ianmenethil•Updated 8 hours ago
5
6/**
7 * Handle API requests
8 */
9export async function handleApiRequest(req: Request): Promise<Response> {
10 const url = new URL(req.url);
11 const path = url.pathname.replace("/api/", "");
12
13 try {
14 // Route to the appropriate API handler
15 if (path === "requests") {
16 const usageId = url.searchParams.get("usage_id");
67 }
68 } catch (error) {
69 console.error("API error:", error);
70 return new Response(JSON.stringify({ error: error.message }), {
71 status: 500,

TownieHome.tsx5 matches

@ianmenethil•Updated 8 hours ago
41 <ol>
42 <li>
43 Login with your Val Town API token (with projects:read, projects:write, user:read permissions)
44 </li>
45 <li>Select a project to work on</li>
79 </div>
80 <h3>Cost Tracking</h3>
81 <p>See estimated API usage costs for each interaction</p>
82 </div>
83 </section>
88 <ul>
89 <li>React frontend with TypeScript</li>
90 <li>Hono API server backend</li>
91 <li>Web Audio API for sound notifications</li>
92 <li>AI SDK for Claude integration</li>
93 </ul>
94 <p>
95 The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
96 project files directly.
97 </p>

Townie.cursorrules10 matches

@ianmenethil•Updated 8 hours 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`

TownieCreditBalance.tsx1 match

@ianmenethil•Updated 8 hours ago
9 const fetchBalance = async () => {
10 try {
11 const response = await fetch("/api/credit-balance");
12 if (response.ok) {
13 const data = await response.json();

Towniecredit-additions.ts1 match

@ianmenethil•Updated 8 hours ago
2import { formatNumber, formatPrice, formatDate } from "../utils/formatters.ts";
3import { PaginationResult, renderPaginationControls } from "../utils/pagination.ts";
4import { CreditAddition } from "../api/credit-additions.ts";
5
6interface CreditAdditionsSummary {

TownieBRANCH-TODO.md6 matches

@ianmenethil•Updated 8 hours ago
52**New Backend Routes:**
53
54* /api/stripe-webhook - Handles payment success, adds credits with signature verification
55
56* /api/purchase-credits - Creates payment intents ($1-$100 validation)
57
58* /api/credit-balance - Returns user's current balance
59
60
981. Create payment links for common amounts ($5, $10, $25, $50)
99
1002. Configure webhook endpoint: https://your-domain.com/api/stripe-webhook
101
1023. Set success URL to redirect back to Townie
151**Balance Calculation:**
152
153Plain textANTLR4BashCC#CSSCoffeeScriptCMakeDartDjangoDockerEJSErlangGitGoGraphQLGroovyHTMLJavaJavaScriptJSONJSXKotlinLaTeXLessLuaMakefileMarkdownMATLABMarkupObjective-CPerlPHPPowerShell.propertiesProtocol BuffersPythonRRubySass (Sass)Sass (Scss)SchemeSQLShellSwiftSVGTSXTypeScriptWebAssemblyYAMLXML` SELECT COALESCE(additions.total, 0) - COALESCE(usage.total, 0) as balance FROM (SELECT SUM(amount) FROM credit_additions WHERE user_id = ?) additions, (SELECT SUM(price * 1.5) FROM townie_usage WHERE user_id = ? AND our_api_token = 1) usage `
154
155**Business Rules:**
179* backend/routes/purchase-credits.ts - NEW: Payment intent creation
180
181* backend/routes/credit-balance.ts - NEW: Balance API
182
183* backend/index.ts - Added new routes

nightbot-master-commandnew-file-9775.tsx4 matches

@jayden•Updated 8 hours ago
41 advice: async () => {
42 console.log("handler.advice");
43 const res = await fetch("https://api.adviceslip.com/advice");
44 if (!res.ok) {
45 console.error("advice fetch failed", res.status);
64 trivia: async () => {
65 console.log("handler.trivia");
66 const res = await fetch("http://numbersapi.com/random/trivia?json");
67 if (!res.ok) {
68 console.error("trivia fetch failed", res.status);
74 compliment: async () => {
75 console.log("handler.compliment");
76 const res = await fetch("https://complimentr.com/api");
77 if (!res.ok) {
78 console.error("compliment fetch failed", res.status);
215
216 // try {
217 // const res = await fetch(`https://ohmanda.com/api/horoscope/${sign}`);
218 // if (!res.ok) {
219 // console.error("horoscope fetch failed", res.status);

ChatREADME.md7 matches

@c15r•Updated 10 hours 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, featuring **centralized client management** and **performance optimizations**.
4
5Source: https://www.val.town/x/c15r/Chat
38const clientPool = new MCPClientPool(connectedClients, serverConfigs);
39
40// Unified API across all components
41await clientPool.testServer(serverName);
42await clientPool.fetchTools();
116
117The app stores configuration and chat history in localStorage:
118- `anthropic_api_key`: Your Anthropic API key
119- `selected_model`: The chosen Claude model (defaults to claude-3-5-sonnet-20241022)
120- `mcp_servers`: Array of configured MCP servers
144For detailed testing information, see [TESTING.md](./TESTING.md).
145
146### API Endpoints
147
148- `GET /` - Main application (serves frontend)
155
1561. Open the app at the provided URL
1572. Click "Settings" in the footer to configure your Anthropic API key and select your preferred Claude model
1583. Add/remove/toggle MCP servers as needed
1594. Use the "Test" button next to each MCP server to verify connectivity (shows ✅ for success, ❌ for errors)
200- **Auto-scroll**: Messages automatically scroll to bottom during streaming
201- **Auto-resize**: Input field grows with content
202- **Error Handling**: Clear error messages for API issues with stream recovery
203- **Loading States**: Visual feedback during API calls and streaming
204- **Structured Responses**: MCP tool use and results are displayed in organized, collapsible sections
205- **Clean Interface**: Maximized chat area with no header, footer contains all controls

ChatStreamingChat.tsx8 matches

@c15r•Updated 10 hours ago
177 /** Retry a user message */
178 const retryMessage = async (messageId: string) => {
179 if (status !== "idle" || !config.anthropicApiKey) return;
180
181 const userText = onRetryFromMessage(messageId);
203 console.log("[Chat] fire send", { userText, input });
204 const messageText = userText || input.trim();
205 if (!messageText || status !== "idle" || !config.anthropicApiKey) return;
206
207 // Only clear input if we're using the current input (not NextSteps execution)
262 };
263
264 const canSend = input?.trim() && status === "idle" && config.anthropicApiKey;
265
266 /* ── UI ─────────────────────────────────────────────────────── */
268 <>
269 <div className="chat-messages">
270 {!config.anthropicApiKey && (
271 <div className="message system">
272 Please configure your Anthropic API key in settings to start chatting
273 </div>
274 )}
379 }}
380 onKeyDown={handleKeyDown}
381 placeholder={config.anthropicApiKey
382 ? streaming
383 ? "Streaming…"
385 ? "Waiting for your input above…"
386 : "Type your message or / for commands…"
387 : "Configure API key in settings first"}
388 className="chat-input"
389 disabled={!config.anthropicApiKey || thinking || waitingForUser}
390 rows={1}
391 />
Plantfo

Plantfo8 file matches

@Llad•Updated 10 hours ago
API for AI plant info

scrapeCraigslistAPI1 file match

@shapedlines•Updated 23 hours ago
apiry
snartapi