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=281&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 12040 results for "api"(1339ms)

val_to_project_converterstyle.css1 match

@charmaineโ€ขUpdated 3 weeks ago
1@import url("https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,400;9..144,500;9..144,600;9..144,700&family=JetBrains+Mono:wght@400;500&display=swap");
2
3:root {

groqAudioChatmain.tsx47 matches

@allโ€ขUpdated 3 weeks ago
6import "jsr:@std/dotenv/load"; // needed for deno run; not req for smallweb or valtown
7
8// Function to handle audio transcription using Groq's Whisper API
9export const audioTranscriptionHandler = async (c) => {
10 console.log("๐ŸŽค Audio transcription request received");
20 }
21
22 // Get API key from environment variable
23 const apiKey = Deno.env.get("GROQ_API_KEY");
24 if (!apiKey) {
25 console.error("โŒ Transcription error: Missing API key");
26 return c.json({ error: "API key not configured" }, 500);
27 }
28
38
39 // If the file doesn't have a proper name or type, add one
40 // This ensures the file has the right extension for the API
41 if (!audioFile.name || !audioFile.type.startsWith("audio/")) {
42 const newFile = new File(
50 }
51
52 // Prepare the form data for Groq API
53 const groqFormData = new FormData();
54
65 groqFormData.append("timestamp_granularities[]", "word");
66
67 // Call Groq API
68 console.log("๐ŸŽค Sending request to Groq Whisper API");
69 const start = Date.now();
70 const response = await fetch("https://api.groq.com/openai/v1/audio/transcriptions", {
71 method: "POST",
72 headers: {
73 "Authorization": `Bearer ${apiKey}`,
74 },
75 body: groqFormData,
76 });
77 const elapsed = Date.now() - start;
78 console.log(`๐ŸŽค Groq Whisper API response received in ${elapsed}ms, status: ${response.status}`);
79
80 // Get response content type
99 errorMessage = `Server error: ${response.status} ${response.statusText}`;
100 // Log the full response for debugging
101 console.error("โŒ Transcription API error response:", {
102 status: response.status,
103 statusText: response.statusText,
108 }
109 } catch (parseError) {
110 console.error("โŒ Error parsing Groq API response:", parseError);
111 errorMessage = "Failed to parse error response from server";
112 }
113
114 return c.json({
115 error: `Groq API error: ${errorMessage}`,
116 status: response.status,
117 }, response.status);
150 console.log(`๐Ÿ”ต Last user message: "${messages.find(m => m.role === "user")?.content?.substring(0, 50)}..."`);
151
152 const GROQ_API_KEY = Deno.env.get("GROQ_API_KEY");
153 if (!GROQ_API_KEY) {
154 console.error("โŒ Missing GROQ_API_KEY environment variable");
155 return c.json({ error: "GROQ_API_KEY environment variable is not set" }, 500);
156 }
157
158 console.log("๐Ÿ”ต Sending request to Groq API");
159 const start = Date.now();
160 const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
161 method: "POST",
162 headers: {
163 "Content-Type": "application/json",
164 "Authorization": `Bearer ${GROQ_API_KEY}`,
165 },
166 body: JSON.stringify({
171 });
172 const elapsed = Date.now() - start;
173 console.log(`๐Ÿ”ต Groq API response received in ${elapsed}ms, status: ${response.status}`);
174
175 if (!response.ok) {
176 const errorData = await response.json();
177 console.error("โŒ Chat API error:", errorData);
178 return c.json({ error: "Failed to get chat completion", details: errorData }, response.status);
179 }
206 }
207
208 // Get API key from environment variable
209 const apiKey = Deno.env.get("GROQ_API_KEY");
210 if (!apiKey) {
211 console.error("โŒ TTS error: Missing API key");
212 return c.json({ error: "API key not configured" }, 500);
213 }
214
215 // Call Groq Speech API
216 console.log("๐Ÿ”Š Sending request to Groq Speech API");
217 const start = Date.now();
218 const response = await fetch("https://api.groq.com/openai/v1/audio/speech", {
219 method: "POST",
220 headers: {
221 "Content-Type": "application/json",
222 "Authorization": `Bearer ${apiKey}`,
223 },
224 body: JSON.stringify({
230 });
231 const elapsed = Date.now() - start;
232 console.log(`๐Ÿ”Š Groq Speech API response received in ${elapsed}ms, status: ${response.status}`);
233
234 if (!response.ok) {
237 const errorData = await response.json();
238 errorMessage = errorData.error?.message || JSON.stringify(errorData);
239 console.error("โŒ TTS API error:", errorData);
240 } catch (e) {
241 // If response is not JSON
242 errorMessage = `Server error: ${response.status} ${response.statusText}`;
243 console.error("โŒ TTS API non-JSON error:", errorMessage);
244 }
245
603 // Now immediately send this message to get AI response
604 try {
605 // Prepare messages for the API
606 const apiMessages = this.messages.map(({ role, content }) => ({ role, content }));
607
608 // Ensure first message is always the correct system message for current mode
609 if (apiMessages.length > 0 && apiMessages[0].role === 'system') {
610 const systemMessage = this.chatMode === 'concise'
611 ? 'You are a helpful assistant powered by the Llama-3.3-70b-versatile model. Keep your responses short, concise and conversational. Aim for 1-3 sentences when possible.'
612 : 'You are a helpful assistant powered by the Llama-3.3-70b-versatile model. Respond conversationally and accurately to the user.';
613
614 apiMessages[0].content = systemMessage;
615 }
616
618 method: 'POST',
619 headers: { 'Content-Type': 'application/json' },
620 body: JSON.stringify({ messages: apiMessages })
621 });
622
681 this.statusMessage = 'Thinking...';
682
683 // Prepare messages for the API (excluding UI-only properties)
684 const apiMessages = this.messages.map(({ role, content }) => ({ role, content }));
685
686 // Ensure first message is always the correct system message for current mode
687 if (apiMessages.length > 0 && apiMessages[0].role === 'system') {
688 const systemMessage = this.chatMode === 'concise'
689 ? 'You are a helpful assistant powered by the Llama-3.3-70b-versatile model. Keep your responses short, concise and conversational. Aim for 1-3 sentences when possible.'
690 : 'You are a helpful assistant powered by the Llama-3.3-70b-versatile model. Respond conversationally and accurately to the user.';
691
692 apiMessages[0].content = systemMessage;
693 }
694
697 method: 'POST',
698 headers: { 'Content-Type': 'application/json' },
699 body: JSON.stringify({ messages: apiMessages })
700 });
701

val_to_project_converterindex.ts10 matches

@charmaineโ€ขUpdated 3 weeks ago
3import { Hono } from "npm:hono";
4import { createProjectFromVals } from "./services/projectService.ts";
5import redirectHandler from "./api/redirect.ts";
6
7const app = new Hono();
19
20// List user's projects
21app.get("/api/projects", async (c) => {
22 const authHeader = c.req.header("Authorization");
23 const apiKey = authHeader?.split("Bearer ")?.[1];
24
25 if (!apiKey) {
26 return c.json({ error: "API key is required" }, 401);
27 }
28
29 try {
30 const projectsResponse = await fetch("https://api.val.town/v1/me/projects?limit=100", {
31 headers: {
32 "Authorization": `Bearer ${apiKey}`,
33 },
34 });
36 if (!projectsResponse.ok) {
37 const errorText = await projectsResponse.text();
38 console.error("Val Town API Error:", errorText);
39 throw new Error(`Failed to fetch projects: ${projectsResponse.statusText}`);
40 }
58app.post("/convert", async (c) => {
59 try {
60 const { apiKey, vals, projectName, existingProjectId } = await c.req.json();
61
62 const result = await createProjectFromVals(apiKey, vals, projectName, existingProjectId);
63
64 return c.json(result);

val_to_project_converterApp.tsx20 matches

@charmaineโ€ขUpdated 3 weeks ago
6
7export function App() {
8 const [apiKey, setApiKey] = useState<string>("");
9 const [valUrlsInput, setValUrlsInput] = useState<string>("");
10 const [projectName, setProjectName] = useState<string>("");
19 const [isLoadingProjects, setIsLoadingProjects] = useState<boolean>(false);
20 const [projectsError, setProjectsError] = useState<string | null>(null);
21 const [apiKeyHighlightError, setApiKeyHighlightError] = useState<boolean>(false);
22
23 useEffect(() => {
24 if (apiKey) {
25 const fetchProjects = async () => {
26 setIsLoadingProjects(true);
29 setSelectedProjectId("");
30 try {
31 const response = await fetch("/api/projects", {
32 headers: {
33 "Authorization": `Bearer ${apiKey}`,
34 },
35 });
45 } catch (err: any) {
46 console.error("Project fetch error:", err);
47 setProjectsError(err.message || "Could not load projects. Ensure your API key is valid.");
48 setCreationMode("new");
49 } finally {
61 }
62 }
63 }, [apiKey]);
64
65 const parseValUrls = (input: string): ValInfo[] => {
92 setResults(null);
93 setRedirectToRedirectPage(false);
94 setApiKeyHighlightError(false);
95
96 const valsToConvert = parseValUrls(valUrlsInput);
103
104 let requestBody: any = {
105 apiKey,
106 vals: valsToConvert,
107 };
146 setIsLoading(false);
147 }
148 }, [apiKey, valUrlsInput, projectName, creationMode, selectedProjectId]);
149
150 const handleRedirectConfirm = async () => {
160 headers: { "Content-Type": "application/json" },
161 body: JSON.stringify({
162 apiKey,
163 originalVals: originalVals,
164 projectName: results.projectName,
186
187 const handleExistingProjectLabelClick = () => {
188 if (!apiKey) {
189 setApiKeyHighlightError(true);
190 setTimeout(() => setApiKeyHighlightError(false), 1500);
191 }
192 };
193
194 const handleApiKeyChange = (value: string) => {
195 setApiKey(value);
196 setResults(null);
197 setError(null);
200 setProjectsError(null);
201 setSelectedProjectId("");
202 setApiKeyHighlightError(false);
203 };
204
226 {!results ? (
227 <ConversionForm
228 apiKey={apiKey}
229 valUrls={valUrlsInput}
230 projectName={projectName}
231 isLoading={isLoading || isLoadingProjects}
232 onApiKeyChange={handleApiKeyChange}
233 onValUrlsChange={setValUrlsInput}
234 onProjectNameChange={setProjectName}
241 isLoadingProjects={isLoadingProjects}
242 projectsError={projectsError}
243 apiKeyHighlightError={apiKeyHighlightError}
244 onExistingProjectLabelClick={handleExistingProjectLabelClick}
245 />

val_to_project_converterindex.html2 matches

@charmaineโ€ขUpdated 3 weeks ago
8 content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
9 >
10 <link rel="preconnect" href="https://fonts.googleapis.com">
11 <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
12 <link
13 href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,400;9..144,500;9..144,600;9..144,700&family=JetBrains+Mono:wght@400;500&display=swap"
14 rel="stylesheet"
15 >

stevensDemosendDailyBrief.ts8 matches

@kahanโ€ขUpdated 3 weeks 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

@kahanโ€ขUpdated 3 weeks 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

@kahanโ€ขUpdated 3 weeks 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

@kahanโ€ขUpdated 3 weeks 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" },

stevensDemoindex.ts11 matches

@kahanโ€ขUpdated 3 weeks ago
26});
27
28// --- API Routes for Memories ---
29
30// GET /api/memories - Retrieve all memories
31app.get("/api/memories", async (c) => {
32 const memories = await getAllMemories();
33 return c.json(memories);
34});
35
36// POST /api/memories - Create a new memory
37app.post("/api/memories", async (c) => {
38 const body = await c.req.json<Omit<Memory, "id">>();
39 if (!body.text) {
44});
45
46// PUT /api/memories/:id - Update an existing memory
47app.put("/api/memories/:id", async (c) => {
48 const id = c.req.param("id");
49 const body = await c.req.json<Partial<Omit<Memory, "id">>>();
66});
67
68// DELETE /api/memories/:id - Delete a memory
69app.delete("/api/memories/:id", async (c) => {
70 const id = c.req.param("id");
71 try {
83// --- Blob Image Serving Routes ---
84
85// GET /api/images/:filename - Serve images from blob storage
86app.get("/api/images/:filename", async (c) => {
87 const filename = c.req.param("filename");
88

social_data_api_project3 file matches

@tsuchi_yaโ€ขUpdated 13 hours ago

simple-scrabble-api1 file match

@bryโ€ขUpdated 3 days ago
socialdata
Affordable & reliable alternative to Twitter API: โžก๏ธ Access user profiles, tweets, followers & timeline data in real-time โžก๏ธ Monitor profiles with nearly instant alerts for new tweets, follows & profile updates โžก๏ธ Simple integration
artivilla
founder @outapint.io vibe coding on val.town. dm me to build custom vals: https://artivilla.com