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/?q=api&page=7&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 18866 results for "api"(2330ms)

Townie2index.ts9 matches

@charmaine•Updated 5 hours ago
1import { basicAuthMiddleware } from "./auth.ts";
2import { handleApiRequest } from "./api/index.ts";
3import { getRequests, getRequestById, getInferenceCallsForRequest, getInferenceTotalsForRequest } from "./api/requests.ts";
4import { getUserSummary } from "./api/user-summary.ts";
5import { getValSummary } from "./api/val-summary.ts";
6import { getInferenceCalls } from "./api/inference-calls.ts";
7import { getCreditAdditions } from "./api/credit-additions.ts";
8import { renderDashboard } from "./views/dashboard.ts";
9import { renderRequests } from "./views/requests.ts";
28 const path = url.pathname;
29
30 // Handle API requests
31 if (path.startsWith("/api/")) {
32 return handleApiRequest(req);
33 }
34

Townie2index.ts5 matches

@charmaine•Updated 5 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,

Townie2Home.tsx5 matches

@charmaine•Updated 5 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>

Townie2.cursorrules10 matches

@charmaine•Updated 5 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`

Townie2CreditBalance.tsx1 match

@charmaine•Updated 5 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();

Townie2credit-additions.ts1 match

@charmaine•Updated 5 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 {

Townie2BRANCH-TODO.md6 matches

@charmaine•Updated 5 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

Loutoken_storage.tsx1 match

@jeffvincent•Updated 6 hours ago
120 const oauthHandler = new LouOAuthHandler();
121
122 console.log(`Calling refresh token API for user: ${userId}`);
123 const newTokenData = await oauthHandler.refreshToken(refreshToken);
124 console.log(`Token refresh successful for user: ${userId}`);

tanstackReactHonoExampleREADME.md5 matches

@laurynas•Updated 6 hours ago
8## Hono
9
10This app uses [Hono](https://hono.dev/) as the API framework. You can think of Hono as a replacement for [ExpressJS](https://expressjs.com/) that works in serverless environments like Val Town or Cloudflare Workers. If you come from Python or Ruby, Hono is also a lot like [Flask](https://github.com/pallets/flask) or [Sinatra](https://github.com/sinatra/sinatra), respectively.
11
12## Serving assets to the frontend
20### `index.html`
21
22The most complicated part of this backend API is serving index.html. In this app (like most apps) we serve it at the root, ie `GET /`.
23
24We *bootstrap* `index.html` with some initial data from the server, so that it gets dynamically injected JSON data without having to make another round-trip request to the server to get that data on the frontend. This is a common pattern for client-side rendered apps.
25
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors
31
32Hono and other API frameworks have a habit of swallowing up Errors. We turn off this default behavior by re-throwing errors, because we think most of the time you'll want to see the full stack trace instead of merely "Internal Server Error". You can customize how you want errors to appear.

val-town-http-mcp-serverconfig.ts7 matches

@prashamtrivedi•Updated 6 hours ago
6 // For remote: expect token in request headers, use local prompt file
7 return {
8 apiToken: null, // Will be set from headers
9 apiBase: "https://api.val.town",
10 cli: {
11 preferCli: false,
22 dotenvConfig({ export: true });
23
24 const API_TOKEN = Deno.env.get("VAL_TOWN_API_TOKEN");
25 if (!API_TOKEN) {
26 console.error("Error: VAL_TOWN_API_TOKEN environment variable is required");
27 Deno.exit(1);
28 }
46 : undefined;
47 return {
48 apiToken: API_TOKEN,
49 apiBase: "https://api.val.town",
50 cli: {
51 preferCli: PREFER_CLI,

shippingAPI1 file match

@dynamic_silver•Updated 2 hours ago

api_zenithpayments_com

@ianmenethil•Updated 11 hours ago
apiry
snartapi