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?q=api&page=53&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 20751 results for "api"(2109ms)

birdfactsWikipediaAPI.ts9 matches

@greasegum•Updated 6 days ago
6}
7
8export class WikipediaAPI {
9 private baseURL = "https://en.wikipedia.org/api/rest_v1";
10
11 async getBirdInfo(birdName: string): Promise<WikipediaResult | null> {
18 headers: {
19 "Accept": "application/json",
20 "User-Agent": "BirdFactsAPI/1.0 (https://val.town)"
21 }
22 });
27 return await this.searchAndGetInfo(birdName);
28 }
29 throw new Error(`Wikipedia API error: ${response.status} ${response.statusText}`);
30 }
31
49 return result;
50 } catch (error) {
51 console.error("Wikipedia API error:", error);
52 return null; // Graceful fallback
53 }
56 private async searchAndGetInfo(birdName: string): Promise<WikipediaResult | null> {
57 try {
58 // Use Wikipedia's search API to find the best match
59 const searchUrl = `https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=${encodeURIComponent(birdName + " bird")}&srlimit=1&origin=*`;
60
61 const searchResponse = await fetch(searchUrl);
96 if (match && match[1]) {
97 const candidate = match[1];
98 // Verify it looks like a scientific name (two words, first capitalized)
99 const parts = candidate.split(' ');
100 if (parts.length === 2 &&
113 try {
114 const pageTitle = this.formatPageTitle(birdName);
115 const url = `https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts|pageimages&exintro=true&explaintext=true&piprop=original&titles=${encodeURIComponent(pageTitle)}&origin=*`;
116
117 const response = await fetch(url);

birdfactsEBirdAPI.ts16 matches

@greasegum•Updated 6 days ago
7}
8
9export class EBirdAPI {
10 private baseURL = "https://api.ebird.org/v2";
11 private apiKey: string | undefined;
12
13 constructor() {
14 this.apiKey = Deno.env.get("EBIRD_API_KEY");
15 }
16
20 };
21
22 if (this.apiKey) {
23 headers["X-eBirdApiToken"] = this.apiKey;
24 }
25
36 if (!response.ok) {
37 if (response.status === 429) {
38 throw new Error("eBird API rate limit exceeded");
39 }
40 throw new Error(`eBird API error: ${response.status} ${response.statusText}`);
41 }
42
44 return data as EBirdObservation[];
45 } catch (error) {
46 console.error("eBird API error:", error);
47 throw error;
48 }
58 if (!response.ok) {
59 if (response.status === 429) {
60 throw new Error("eBird API rate limit exceeded");
61 }
62 throw new Error(`eBird API error: ${response.status} ${response.statusText}`);
63 }
64
66 return data as EBirdObservation[];
67 } catch (error) {
68 console.error("eBird API error:", error);
69 throw error;
70 }
79
80 if (!response.ok) {
81 throw new Error(`eBird API error: ${response.status} ${response.statusText}`);
82 }
83
85 return data;
86 } catch (error) {
87 console.error("eBird hotspots API error:", error);
88 throw error;
89 }
99
100 if (!response.ok) {
101 throw new Error(`eBird API error: ${response.status} ${response.statusText}`);
102 }
103
105 return data as EBirdObservation[];
106 } catch (error) {
107 console.error("eBird notable observations API error:", error);
108 throw error;
109 }

birdfactsBirdFactsService.ts15 matches

@greasegum•Updated 6 days ago
1import { blob } from "https://esm.town/v/std/blob";
2import { EBirdAPI } from "./EBirdAPI.ts";
3import { APINinjasAPI } from "./APINinjasAPI.ts";
4import { WikipediaAPI } from "./WikipediaAPI.ts";
5
6export interface BirdFactRequest {
32
33export class BirdFactsService {
34 private eBirdAPI: EBirdAPI;
35 private apiNinjasAPI: APINinjasAPI;
36 private wikipediaAPI: WikipediaAPI;
37 private cachePrefix = "bird_facts_";
38 private regionalCachePrefix = "regional_birds_";
40
41 constructor() {
42 this.eBirdAPI = new EBirdAPI();
43 this.apiNinjasAPI = new APINinjasAPI();
44 this.wikipediaAPI = new WikipediaAPI();
45 }
46
54 } else if (request.lat && request.lng) {
55 // Get region from coordinates and then birds
56 const nearbyBirds = await this.eBirdAPI.getNearbyBirds(request.lat, request.lng);
57 birds = nearbyBirds;
58 region = `${request.lat.toFixed(2)},${request.lng.toFixed(2)}`;
92
93 try {
94 const birds = await this.eBirdAPI.getRegionalBirds(regionCode);
95
96 // Cache the results
158 // Fetch data from multiple sources concurrently
159 const [ninjasFact, wikipediaData] = await Promise.allSettled([
160 this.apiNinjasAPI.getBirdFact(bird.comName),
161 this.wikipediaAPI.getBirdInfo(bird.comName)
162 ]);
163
164 // Add API Ninjas fact if available
165 if (ninjasFact.status === 'fulfilled' && ninjasFact.value) {
166 result.fact = ninjasFact.value;
176 }
177
178 // If we don't have a fact from API Ninjas, try to extract one from Wikipedia
179 if (!result.fact && result.wikipedia?.summary) {
180 result.fact = this.extractFactFromWikipedia(result.wikipedia.summary);

strivemain.tsx16 matches

@join•Updated 6 days ago
157 <script>
158 (function() {
159 const apiUrl = '${sourceUrl}api';
160 const app = document.getElementById('app-container');
161 const nav = document.getElementById('main-nav');
162 let state = { token: localStorage.getItem('strive_token') };
163
164 // --- API CLIENT ---
165 async function resilientFetch(path, options = {}) {
166 options.headers = { ...options.headers, 'Content-Type': 'application/json' };
167 if (state.token) options.headers['Authorization'] = \`Bearer \${state.token}\`;
168
169 const response = await fetch(\`\${apiUrl}\${path}\`, options);
170 if (!response.ok) {
171 const err = await response.json();
172 throw new Error(err.error || 'API request failed');
173 }
174 return response.status === 204 ? null : response.json();
175 }
176
177 const api = {
178 login: (username, secret_phrase) => resilientFetch('/login', { method: 'POST', body: JSON.stringify({ username, secret_phrase }) }),
179 register: (username, secret_phrase) => resilientFetch('/register', { method: 'POST', body: JSON.stringify({ username, secret_phrase }) }),
180 getFeed: () => resilientFetch('/feed'),
181 // Add all other api methods here...
182 };
183
254 }
255
256 // --- API ROUTING ---
257 if (path.startsWith("/api/")) {
258 try {
259 const userId = await verifyAuth(req);
260
261 // --- Unprotected Routes ---
262 if (path === "/api/register" && req.method === "POST") {
263 const { username, secret_phrase } = body as any;
264 if (!username || !secret_phrase) return jsonResponse({ error: "Username and secret phrase required" }, 400);
270 return jsonResponse({ message: "User registered" }, 201);
271 }
272 if (path === "/api/login" && req.method === "POST") {
273 const { username, secret_phrase } = body as any;
274 const hashed = await hashToken(secret_phrase);
288
289 // --- Habit CRUD ---
290 if (path === "/api/habits" && req.method === "POST") {
291 const { name, is_public } = body as any;
292 const id = crypto.randomUUID();
299 }
300
301 const habitMatch = path.match(/^\/api\/habits\/([a-zA-Z0-9\-]+)$/);
302 if (habitMatch && req.method === "DELETE") {
303 const habitId = habitMatch[1];
307
308 // --- AI Routes ---
309 const aiTipsMatch = path.match(/^\/api\/habits\/(?<habitId>[a-zA-Z0-9\-]+)\/ai-tips$/);
310 if (aiTipsMatch && req.method === "POST") {
311 const { habitId } = aiTipsMatch.groups;
334 }
335
336 const aiAffirmationsMatch = path.match(/^\/api\/habits\/(?<habitId>[a-zA-Z0-9\-]+)\/ai-affirmations$/);
337 if (aiAffirmationsMatch && req.method === "POST") {
338 const { habitId } = aiAffirmationsMatch.groups;
365
366 // --- Feed ---
367 if (path === "/api/feed" && req.method === "GET") {
368 const { rows } = await sqlite.execute({
369 sql: `
380
381 // All other routes...
382 return jsonResponse({ error: "API route not found or method not allowed." }, 404);
383 } catch (e) {
384 console.error(e);

socraticmain.tsx11 matches

@join•Updated 6 days ago
134 <meta name="viewport" content="width=device-width, initial-scale=1.0">
135 <title>The Reflective Chamber</title>
136 <link rel="preconnect" href="https://fonts.googleapis.com">
137 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
138 <link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400..700;1,400..700&family=Source+Sans+3:wght@300;400;600&display=swap" rel="stylesheet">
139<style>
140 :root {
340<script>
341(function() {
342 const API_URL = '${sourceUrl}';
343 const affirmations = ${JSON.stringify(affirmations)};
344
419
420 try {
421 const guidance = await resilientFetch(\`\${API_URL}api/reframe\`, {
422 method: 'POST',
423 headers: { 'Content-Type': 'application/json' },
439}
440
441// --- API & ROUTING LOGIC ---
442
443const app = new Hono();
450});
451
452// Middleware for CORS, allowing the frontend to call the API.
453app.use(
454 "/api/*",
455 cors({
456 origin: "*", // In a real application, restrict this to the specific val's domain.
479}
480
481// API endpoint to analyze an entry and provide guidance.
482app.post("/api/reframe", async (c) => {
483 const { entry_text } = await c.req.json();
484 const openai = new OpenAI();
546 const url = new URL(req.url);
547
548 // Route API requests to Hono.
549 if (url.pathname.startsWith("/api/")) {
550 return app.fetch(req);
551 }

myNewWebsiteindex.ts2 matches

@derekbrimley•Updated 6 days ago
12app.get("/frontend/**/*", c => serveFile(c.req.path, import.meta.url));
13
14// Add your API routes here
15// app.get("/api/data", c => c.json({ hello: "world" }));
16
17// Unwrap and rethrow Hono errors as the original error

stevensDemosendDailyBrief.ts8 matches

@derekbrimley•Updated 6 days ago
97
98export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99 // Get API keys from environment
100 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
101 const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
102
106 }
107
108 if (!apiKey) {
109 console.error("Anthropic API key is not configured.");
110 return;
111 }
122
123 // Initialize Anthropic client
124 const anthropic = new Anthropic({ apiKey });
125
126 // Initialize Telegram bot
162
163 // disabled title for now, it seemes unnecessary...
164 // await bot.api.sendMessage(chatId, `*${title}*`, { parse_mode: "Markdown" });
165
166 // Then send the main content
169
170 if (content.length <= MAX_LENGTH) {
171 await bot.api.sendMessage(chatId, content, { parse_mode: "Markdown" });
172 // Store the briefing in chat history
173 await storeChatMessage(
198 // Send each chunk as a separate message and store in chat history
199 for (const chunk of chunks) {
200 await bot.api.sendMessage(chatId, chunk, { parse_mode: "Markdown" });
201 // Store each chunk in chat history
202 await storeChatMessage(

stevensDemoREADME.md1 match

@derekbrimley•Updated 6 days ago
53You'll need to set up some environment variables to make it run.
54
55- `ANTHROPIC_API_KEY` for LLM calls
56- You'll need to follow [these instructions](https://docs.val.town/integrations/telegram/) to make a telegram bot, and set `TELEGRAM_TOKEN`. You'll also need to get a `TELEGRAM_CHAT_ID` in order to have the bot remember chat contents.
57- For the Google Calendar integration you'll need `GOOGLE_CALENDAR_ACCOUNT_ID` and `GOOGLE_CALENDAR_CALENDAR_ID`. See [these instuctions](https://www.val.town/v/stevekrouse/pipedream) for details.

stevensDemoREADME.md5 matches

@derekbrimley•Updated 6 days 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.

stevensDemoNotebookView.tsx5 matches

@derekbrimley•Updated 6 days ago
8import { type Memory } from "../../shared/types.ts";
9
10const API_BASE = "/api/memories";
11const MEMORIES_PER_PAGE = 20;
12
71 setError(null);
72 try {
73 const response = await fetch(API_BASE);
74 if (!response.ok) {
75 throw new Error(`HTTP error! status: ${response.status}`);
100
101 try {
102 const response = await fetch(API_BASE, {
103 method: "POST",
104 headers: { "Content-Type": "application/json" },
123
124 try {
125 const response = await fetch(`${API_BASE}/${id}`, {
126 method: "DELETE",
127 });
155
156 try {
157 const response = await fetch(`${API_BASE}/${editingMemory.id}`, {
158 method: "PUT",
159 headers: { "Content-Type": "application/json" },

claude-api1 file match

@ziyanwould•Updated 3 days ago

api-workshop

@danarddanielsjr•Updated 4 days ago
replicate
Run AI with an API
fiberplane
Purveyors of Hono tooling, API Playground enthusiasts, and creators of 🪿 HONC 🪿 (https://honc.dev)