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/$%7BsvgDataUrl%7D?q=api&page=39&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 19337 results for "api"(2200ms)

stevensDemoindex.ts11 matches

@lurstโ€ขUpdated 2 days ago
18});
19
20// --- API Routes for Memories ---
21
22// GET /api/memories - Retrieve all memories
23app.get("/api/memories", async (c) => {
24 const memories = await getAllMemories();
25 return c.json(memories);
26});
27
28// POST /api/memories - Create a new memory
29app.post("/api/memories", async (c) => {
30 const body = await c.req.json<Omit<Memory, "id">>();
31 if (!body.text) {
36});
37
38// PUT /api/memories/:id - Update an existing memory
39app.put("/api/memories/:id", async (c) => {
40 const id = c.req.param("id");
41 const body = await c.req.json<Partial<Omit<Memory, "id">>>();
58});
59
60// DELETE /api/memories/:id - Delete a memory
61app.delete("/api/memories/:id", async (c) => {
62 const id = c.req.param("id");
63 try {
75// --- Blob Image Serving Routes ---
76
77// GET /api/images/:filename - Serve images from blob storage
78app.get("/api/images/:filename", async (c) => {
79 const filename = c.req.param("filename");
80

stevensDemoindex.html2 matches

@lurstโ€ขUpdated 2 days ago
12 type="image/svg+xml"
13 />
14 <link rel="preconnect" href="https://fonts.googleapis.com" />
15 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
16 <link
17 href="https://fonts.googleapis.com/css2?family=Pixelify+Sans:wght@400..700&display=swap"
18 rel="stylesheet"
19 />

stevensDemohandleUSPSEmail.ts5 matches

@lurstโ€ขUpdated 2 days ago
85 console.log(e.text);
86
87 // Get Anthropic API key from environment
88 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
89 if (!apiKey) {
90 console.error("Anthropic API key is not configured for this val.");
91 return;
92 }
93
94 // Initialize Anthropic client
95 const anthropic = new Anthropic({ apiKey });
96
97 // Process each image attachment serially

stevensDemohandleTelegramMessage.ts7 matches

@lurstโ€ขUpdated 2 days ago
92
93/**
94 * Format chat history for Anthropic API
95 */
96function formatChatHistoryForAI(history) {
321bot.on("message", async (ctx) => {
322 try {
323 // Get Anthropic API key from environment
324 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
325 if (!apiKey) {
326 console.error("Anthropic API key is not configured.");
327 ctx.reply(
328 "I apologize, but I'm not properly configured at the moment. Please inform the household administrator."
332
333 // Initialize Anthropic client
334 const anthropic = new Anthropic({ apiKey });
335
336 // Get message text and user info
502 // Set webhook if it is not set yet
503 if (!isEndpointSet) {
504 await bot.api.setWebhook(req.url, {
505 secret_token: SECRET_TOKEN,
506 });

stevensDemogetWeather.ts5 matches

@lurstโ€ขUpdated 2 days ago
27async function generateConciseWeatherSummary(weatherDay) {
28 try {
29 // Get API key from environment
30 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
31 if (!apiKey) {
32 console.error("Anthropic API key is not configured.");
33 return null;
34 }
35
36 // Initialize Anthropic client
37 const anthropic = new Anthropic({ apiKey });
38
39 const response = await anthropic.messages.create({

stevensDemogenerateFunFacts.ts5 matches

@lurstโ€ขUpdated 2 days ago
77async function generateFunFacts(previousFacts) {
78 try {
79 // Get API key from environment
80 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
81 if (!apiKey) {
82 console.error("Anthropic API key is not configured.");
83 return null;
84 }
85
86 // Initialize Anthropic client
87 const anthropic = new Anthropic({ apiKey });
88
89 // Format previous facts for the prompt

stevensDemo.cursorrules10 matches

@lurstโ€ขUpdated 2 days ago
20### 2. HTTP Vals
21
22- Create web APIs and endpoints
23- Handle HTTP requests and responses
24- Example structure:
66- Generate code in TypeScript
67- Add appropriate TypeScript types and interfaces for all data structures
68- Prefer official SDKs or libraries than writing API calls directly
69- Ask the user to supply API or library documentation if you are at all unsure about it
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
190- For AI-generated images, use: `https://maxm-imggenurl.web.val.run/the-description-of-your-image`
191- **Storage:** DO NOT use the Deno KV module for storage
192- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
193- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
194- **View Source:** Add a view source link with `import.meta.url.replace("esm.town", "val.town")` and include `target="_top"` attribute
195- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
196- **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
197- **Environment Variables:** Use `Deno.env.get('keyname')` and minimize their use - prefer APIs without keys
198- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
199- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
230
231### Backend (Hono) Best Practices
232- Hono is the recommended API framework (similar to Express, Flask, or Sinatra)
233- Main entry point should be `backend/index.ts`
234- **Static asset serving:** Use the utility functions to read and serve project files:
251 });
252 ```
253- Create RESTful API routes for CRUD operations
254- Be careful with error handling as Hono tends to swallow errors
255- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
268- Use React 18.2.0 consistently in all imports and the `@jsxImportSource` pragma
269- Follow the React component pattern from the example project
270- Handle API calls properly with proper error catching
271
272### Database Patterns
299 - For files in the project, use `readFile` helpers
300
3015. **API Design:**
302 - `fetch` handler is the entry point for HTTP vals
303 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`

stevensDemoApp.tsx8 matches

@lurstโ€ขUpdated 2 days ago
10import { NotebookView } from "./NotebookView.tsx";
11
12const API_BASE = "/api/memories";
13const MEMORIES_PER_PAGE = 20; // Increased from 7 to 20 memories per page
14
90
91 // Fetch avatar image
92 fetch("/api/images/stevens.jpg")
93 .then((response) => {
94 if (response.ok) return response.blob();
104
105 // Fetch wood background
106 fetch("/api/images/wood.jpg")
107 .then((response) => {
108 if (response.ok) return response.blob();
133 setError(null);
134 try {
135 const response = await fetch(API_BASE);
136 if (!response.ok) {
137 throw new Error(`HTTP error! status: ${response.status}`);
176
177 try {
178 const response = await fetch(API_BASE, {
179 method: "POST",
180 headers: { "Content-Type": "application/json" },
199
200 try {
201 const response = await fetch(`${API_BASE}/${id}`, {
202 method: "DELETE",
203 });
231
232 try {
233 const response = await fetch(`${API_BASE}/${editingMemory.id}`, {
234 method: "PUT",
235 headers: { "Content-Type": "application/json" },
606 <div className="font-pixel text-[#f8f1e0]">
607 <style jsx>{`
608 @import url("https://fonts.googleapis.com/css2?family=Pixelify+Sans&display=swap");
609
610 @tailwind base;

reactHonoStarterindex.ts2 matches

@Hi123โ€ขUpdated 2 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
Plantfo

PlantfoREADME.md32 matches

@Lladโ€ขUpdated 2 days ago
1# Plant Information API
2
3A REST API that provides detailed plant information using OpenAI's GPT model with intelligent caching for improved performance and reduced API costs.
4
5## Project Structure
10โ”‚ โ””โ”€โ”€ database/
11โ”‚ โ””โ”€โ”€ cache.ts # Database cache functions
12โ”œโ”€โ”€ test.html # Plant API testing interface
13โ”œโ”€โ”€ admin.html # Cache admin interface
14โ””โ”€โ”€ README.md
25- Automatic plant name normalization for consistent caching
26
27## API Endpoints
28
29### GET /
30Simple testing interface for the Plant API with comprehensive features:
31- **Interactive plant lookup**: Enter plant names and see real-time API responses
32- **API documentation**: Built-in instructions showing all available endpoints and usage examples
33- **Request URL display**: Shows the exact URL used for each request with copy-to-clipboard functionality
34- **Response formatting**: Pretty-printed JSON responses with syntax highlighting
35- **Error handling**: Clear display of API errors and network issues
36- **Admin panel access**: Direct link to cache management interface
37- **Caching indicators**: Visual feedback showing whether responses came from cache or fresh API calls
38
39### GET /api
40Returns API information, usage instructions, and cache statistics.
41
42### GET /admin
102
103### GET /health
104Health check endpoint that returns API status.
105
106### GET /cache/stats
180## Authentication
181
182The API includes a secure authentication system to protect admin features and cache management endpoints.
183
184### Environment Variables
196The following endpoints require admin authentication:
197- `/admin` - Admin interface
198- `/admin/cache/full` - Full cache data API
199- `/cache/stats` - Cache statistics
200- `/cache/list` - List cached plants
210## Error Handling
211
212The API returns appropriate HTTP status codes:
213- `200`: Success
214- `400`: Bad request (missing plant name)
215- `401`: Unauthorized (authentication required)
216- `500`: Server error (OpenAI API issues, parsing errors)
217
218Error responses include descriptive error messages and may include additional debugging information.
222```bash
223# Access the testing interface (web browser)
224# Visit: https://your-api-url/
225
226# Get API information and statistics
227curl https://your-api-url/api
228
229# Get information about a rose (will cache the response)
230curl https://your-api-url/plant/rose
231
232# Get information about the same rose again (will return cached response)
233curl https://your-api-url/plant/rose
234
235# Get information about a tomato plant
236curl https://your-api-url/plant/tomato
237
238# Get information about a Japanese maple (spaces are handled automatically)
239curl https://your-api-url/plant/japanese%20maple
240
241# Check cache statistics (requires authentication)
242curl -b cookies.txt https://your-api-url/cache/stats
243
244# List all cached plants (requires authentication)
245curl -b cookies.txt https://your-api-url/cache/list
246
247# Clear the cache (requires authentication)
248curl -X POST -b cookies.txt https://your-api-url/cache/clear
249
250# Access the admin interface (web browser, requires login)
251# Visit: https://your-api-url/admin
252
253# Login page (web browser)
254# Visit: https://your-api-url/login
255```
256
258
259- **Plant name normalization**: Plant names are normalized (lowercased, special characters removed, spaces converted to underscores) for consistent caching
260- **Cache hits**: Subsequent requests for the same plant (even with different capitalization or spacing) will return cached responses instantly
261- **Cache misses**: New plants trigger OpenAI API calls and the responses are automatically cached
262- **Performance**: Cached responses are served in milliseconds vs. seconds for OpenAI API calls
263- **Cost efficiency**: Reduces OpenAI API usage and associated costs
264
265## Technical Details

researchAgent2 file matches

@thesephistโ€ขUpdated 11 hours ago
This is a lightweight wrapper around Perplexity's web search API

memoryApiExample2 file matches

@ingenierotitoโ€ขUpdated 12 hours ago
apiry
snartapi