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=288&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 11992 results for "api"(1150ms)

stevensDemo.cursorrules10 matches

@fcouryUpdated 3 weeks 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

@fcouryUpdated 3 weeks 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;
isbn_list

isbn_listindex.ts2 matches

@nick_bensonUpdated 3 weeks 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
vtProjectSearch

vtProjectSearchstyles.tsx4 matches

@maxmUpdated 3 weeks ago
782}
783
784.api-info {
785 margin-top: 10px;
786}
787
788.api-info summary {
789 cursor: pointer;
790 color: var(--primary-color);
792}
793
794.api-docs {
795 background-color: var(--code-bg);
796 padding: 10px 15px;
801}
802
803.api-docs code {
804 display: inline-block;
805 background-color: white;
vtProjectSearch

vtProjectSearchcomponents.tsx8 matches

@maxmUpdated 3 weeks ago
1063 <link rel="icon" href="https://fav.farm/👀" />
1064 <meta name="viewport" content="width=device-width, initial-scale=1" />
1065 <link rel="preconnect" href="https://fonts.googleapis.com" />
1066 <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
1067 <link
1068 href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,100..700;1,100..700&display=swap"
1069 rel="stylesheet"
1070 />
1080 <a href="https://val.town" className="valtown-link" style={{ marginLeft: "auto" }}>Return to Val Town</a>
1081 </h1>
1082 <div className="api-info">
1083 <details>
1084 <summary>API Access</summary>
1085 <div className="api-docs">
1086 <p>
1087 You can access search results via JSON API by adding <code>format=json</code> to your query:
1088 </p>
1089 {searchTerm
1241 <div className="search-examples">
1242 <a href="?q=fetch" className="example-link">fetch</a>
1243 <a href="?q=api" className="example-link">api</a>
1244 <a href="?q=database" className="example-link">database</a>
1245 <a href="?q=image" className="example-link">image</a>
1396 <div className="search-examples">
1397 <a href="?q=fetch" className="example-link">fetch</a>
1398 <a href="?q=api" className="example-link">api</a>
1399 <a href="?q=database" className="example-link">database</a>
1400 <a href="?q=image" className="example-link">image</a>

telegramBotStarterindex.ts1 match

@WaryaaUpdated 3 weeks ago
30 // This is a no-op if nothing's changed
31 if (!isEndpointSet) {
32 await bot.api.setWebhook(req.url, {
33 secret_token: SECRET_TOKEN,
34 });

x_posts_collect_mainmain.tsx59 matches

@tsuchi_yaUpdated 3 weeks ago
10 const [query, setQuery] = React.useState("");
11 const [targetAccount, setTargetAccount] = React.useState("");
12 const [apiKey, setApiKey] = React.useState("");
13 const [searchType, setSearchType] = React.useState("Latest");
14 const [sinceDate, setSinceDate] = React.useState("");
39 const checkAuth = async () => {
40 try {
41 const response = await fetch("/api/me");
42 if (response.ok) {
43 const userData = await response.json();
97 setAuthError(null);
98 try {
99 const response = await fetch("/api/login", {
100 method: "POST",
101 headers: { "Content-Type": "application/json" },
120 setAuthError(null);
121 try {
122 const response = await fetch("/api/register", {
123 method: "POST",
124 headers: { "Content-Type": "application/json" },
138 const handleLogout = async () => {
139 try {
140 await fetch("/api/logout");
141 setUser(null);
142 // Clear sensitive data on logout
143 setApiKey("");
144 setTweets([]);
145 setError(null);
154 // No need to check for user here, useEffect handles it
155 try {
156 const response = await fetch("/api/searches");
157 if (response.ok) {
158 const searches = await response.json();
186 if (!searchName) return;
187
188 const response = await fetch("/api/searches/save", {
189 method: "POST",
190 headers: { "Content-Type": "application/json" },
214 if (!confirm("Are you sure you want to delete this saved search?")) return;
215 try {
216 const response = await fetch(`/api/searches/${searchId}/delete`, {
217 method: "POST", // Using POST due to potential Val Town limitations
218 });
242 search.until_date,
243 );
244 // Ensure API key is present before running saved search
245 if (!apiKey.trim()) {
246 setError(
247 "Please enter your SocialData API Key before running a saved search.",
248 );
249 return;
261 return;
262 }
263 if (!apiKey.trim()) {
264 setError("Please enter your SocialData API Key.");
265 return;
266 }
289 params.append("cursor", currentCursor);
290 }
291 // *** Pass API key in header ***
292 const response = await fetch(`/api/search?${params.toString()}`, {
293 headers: { "X-Api-Key": apiKey }, // Pass API key here
294 });
295
306 const errorData = await response
307 .json()
308 .catch(() => ({ message: `API Error: ${response.statusText}` }));
309 throw new Error(
310 errorData.message
311 || `API Error: ${response.statusText} on page ${pageNum}`,
312 );
313 }
318 if (data.status === "error") {
319 throw new Error(
320 data.message || `API returned an error on page ${pageNum}`,
321 );
322 }
353 }
354 },
355 [apiKey, user], // Add user dependency
356 );
357
367 return;
368 }
369 if (!apiKey.trim()) {
370 setError("Please enter your SocialData API Key.");
371 return;
372 }
562 rel: "noopener noreferrer",
563 },
564 "SocialData API",
565 ),
566 " | ",
616 ),
617 ),
618 // --- API Key Input ---
619 React.createElement(
620 "div",
625 React.createElement(
626 "label",
627 { htmlFor: "apiKey", className: "label" },
628 "API Key",
629 ),
630 React.createElement("input", {
631 type: "password",
632 id: "apiKey",
633 value: apiKey,
634 onChange: (e) => setApiKey(e.target.value),
635 placeholder: "Enter SocialData API Key",
636 className: "input",
637 }),
1088 rel: "noopener noreferrer",
1089 },
1090 "SocialData API",
1091 ),
1092 " | ",
1194 }
1195
1196 // --- API Endpoints ---
1197
1198 // Register Endpoint
1199 if (url.pathname === "/api/register" && request.method === "POST") {
1200 try {
1201 const { username, email, password } = await request.json();
1247
1248 // Login Endpoint
1249 if (url.pathname === "/api/login" && request.method === "POST") {
1250 try {
1251 const { email, password } = await request.json();
1290
1291 // Get Current User Endpoint
1292 if (url.pathname === "/api/me" && request.method === "GET") {
1293 try {
1294 const user = await getUserFromRequest(request);
1325
1326 // Logout Endpoint
1327 if (url.pathname === "/api/logout" && request.method === "GET") {
1328 // Changed to GET for simplicity, POST is often preferred
1329 return Response.json(
1341
1342 // Save Search Endpoint
1343 if (url.pathname === "/api/searches/save" && request.method === "POST") {
1344 if (!user)
1345 return Response.json({ error: "Not authenticated" }, { status: 401 });
1395
1396 // Get Saved Searches Endpoint
1397 if (url.pathname === "/api/searches" && request.method === "GET") {
1398 if (!user)
1399 return Response.json({ error: "Not authenticated" }, { status: 401 });
1415 // Delete Saved Search Endpoint
1416 if (
1417 url.pathname.startsWith("/api/searches/")
1418 && url.pathname.endsWith("/delete")
1419 && (request.method === "POST" || request.method === "DELETE")
1447 }
1448
1449 // Search API Proxy Endpoint
1450 if (url.pathname === "/api/search" && request.method === "GET") {
1451 // *** LOGIN CHECK ADDED for the proxy endpoint ***
1452 if (!user) {
1457 }
1458
1459 const apiKey = request.headers.get("X-Api-Key"); // Get API key from header sent by frontend
1460 if (!apiKey) {
1461 return Response.json(
1462 { status: "error", message: "API Key missing in request" },
1463 { status: 400 },
1464 ); // Changed status to 400
1476 }
1477
1478 const apiUrl = new URL("https://api.socialdata.tools/twitter/search");
1479 apiUrl.searchParams.set("query", query);
1480 apiUrl.searchParams.set("type", type);
1481 if (cursor) apiUrl.searchParams.set("cursor", cursor);
1482
1483 try {
1484 const apiResponse = await fetch(apiUrl.toString(), {
1485 headers: {
1486 Authorization: `Bearer ${apiKey}`, // Use the API key from the request header
1487 Accept: "application/json",
1488 },
1491 let responseData;
1492 try {
1493 responseData = await apiResponse.json();
1494 } catch (e) {
1495 const text = await apiResponse.text();
1496 console.error("Non-JSON response from SocialData:", text);
1497 return Response.json(
1498 {
1499 status: "error",
1500 message: `SocialData API non-JSON response: ${apiResponse.statusText}`,
1501 },
1502 { status: apiResponse.status },
1503 );
1504 }
1505
1506 if (!apiResponse.ok || responseData.status === "error") {
1507 console.error(
1508 `SocialData API Error (${apiResponse.status}):`,
1509 responseData,
1510 );
1514 status: "error",
1515 message: responseData?.message
1516 || `SocialData API Error: ${apiResponse.statusText}`,
1517 },
1518 { status: apiResponse.status },
1519 );
1520 }

test01main.tsx57 matches

@tsuchi_yaUpdated 3 weeks ago
9 const [query, setQuery] = React.useState("");
10 const [targetAccount, setTargetAccount] = React.useState("");
11 const [apiKey, setApiKey] = React.useState("");
12 const [searchType, setSearchType] = React.useState("Latest");
13 const [sinceDate, setSinceDate] = React.useState("");
35 const checkAuth = async () => {
36 try {
37 const response = await fetch("/api/me"); // サーバーに現在のユーザー情報を問い合わせる
38 if (response.ok) {
39 const userData = await response.json(); // 応答がOKならユーザーデータを取得
57 if (!user) return; // ユーザーがログインしていない場合は何もしない(※useEffectの後に移動したのでこのチェックは不要かも)
58 try {
59 const response = await fetch("/api/searches"); // 保存済み検索APIを叩く
60 if (response.ok) {
61 const searches = await response.json();
94
95 try {
96 const response = await fetch("/api/login", {
97 // ログインAPIを叩く
98 method: "POST",
99 headers: { "Content-Type": "application/json" },
125
126 try {
127 const response = await fetch("/api/register", {
128 // 登録APIを叩く
129 method: "POST",
130 headers: { "Content-Type": "application/json" },
148 const handleLogout = async () => {
149 try {
150 await fetch("/api/logout"); // ログアウトAPIを叩く
151 setUser(null); // ユーザー情報をnullにする
152 // setSavedSearches([]); // useEffectでuserが変わると自動でクリアされるので不要
178 if (!searchName) return; // キャンセルされたら何もしない
179
180 const response = await fetch("/api/searches/save", {
181 // 保存APIを叩く
182 method: "POST",
183 headers: { "Content-Type": "application/json" },
212
213 try {
214 const response = await fetch(`/api/searches/${searchId}/delete`, {
215 method: "POST", // Val Townの制限でDELETEが使えない場合があるのでPOSTを使う
216 });
279 const fetchAllTweets = React.useCallback(
280 async (fullQuery, type, targetCount) => {
281 if (!apiKey.trim()) {
282 setError("Please enter your SocialData API Key.");
283 return;
284 }
306 params.append("cursor", currentCursor);
307 }
308 const response = await fetch(`/api/search?${params.toString()}`, {
309 headers: { "X-Api-Key": apiKey },
310 });
311 if (!isFetchingRef.current) break;
313 const errorData = await response
314 .json()
315 .catch(() => ({ message: `API Error: ${response.statusText}` }));
316 throw new Error(
317 errorData.message ||
318 `API Error: ${response.statusText} on page ${pageNum}`
319 );
320 }
323 if (data.status === "error") {
324 throw new Error(
325 data.message || `API returned an error on page ${pageNum}`
326 );
327 }
356 }
357 },
358 [apiKey]
359 );
360
365 return;
366 }
367 if (!apiKey.trim()) {
368 setError("Please enter your SocialData API Key.");
369 return;
370 }
596 )
597 ),
598 // API Key Section
599 React.createElement(
600 "div",
605 React.createElement(
606 "label",
607 { htmlFor: "apiKey", className: "label" },
608 "API Key"
609 ),
610 React.createElement("input", {
611 type: "password",
612 id: "apiKey",
613 value: apiKey,
614 onChange: (e) => setApiKey(e.target.value),
615 placeholder: "Enter SocialData API Key",
616 className: "input",
617 })
1081 rel: "noopener noreferrer",
1082 },
1083 "SocialData API"
1084 ),
1085 " | ",
1201
1202 // テーブル確認用エンドポイント
1203 if (url.pathname === "/api/check-table") {
1204 try {
1205 const result = await sqlite.execute(`
1222
1223 // ヘルパー関数テスト用エンドポイント(単純化)
1224 if (url.pathname === "/api/test-helpers") {
1225 try {
1226 // パスワードハッシュ化のテスト
1247
1248 // ユーザー登録エンドポイント
1249 if (url.pathname === "/api/register") {
1250 if (request.method !== "POST") {
1251 return Response.json({ error: "Method not allowed" }, { status: 405 });
1338
1339 // ユーザーログインエンドポイント
1340 if (url.pathname === "/api/login") {
1341 if (request.method !== "POST") {
1342 return Response.json({ error: "Method not allowed" }, { status: 405 });
1409
1410 // 現在のユーザー情報取得エンドポイント
1411 if (url.pathname === "/api/me") {
1412 try {
1413 // ユーザー情報を取得
1446
1447 // ログアウトエンドポイント
1448 if (url.pathname === "/api/logout") {
1449 return Response.json(
1450 { success: true },
1460
1461 // 検索条件保存エンドポイント
1462 if (url.pathname === "/api/searches/save") {
1463 if (request.method !== "POST") {
1464 return Response.json({ error: "Method not allowed" }, { status: 405 });
1545
1546 // 保存済み検索一覧取得エンドポイント
1547 if (url.pathname === "/api/searches") {
1548 try {
1549 // ユーザー情報を取得
1575 // 保存済み検索削除エンドポイント
1576 if (
1577 url.pathname.startsWith("/api/searches/") &&
1578 url.pathname.includes("/delete")
1579 ) {
1625 }
1626
1627 // 既存のAPI検索エンドポイント
1628 if (url.pathname === "/api/search") {
1629 const apiKey = request.headers.get("X-Api-Key");
1630 if (!apiKey) {
1631 return Response.json(
1632 { status: "error", message: "API Key missing" },
1633 { status: 401 }
1634 );
1643 );
1644 }
1645 const apiUrl = new URL("https://api.socialdata.tools/twitter/search");
1646 apiUrl.searchParams.set("query", query);
1647 apiUrl.searchParams.set("type", type);
1648 if (cursor) apiUrl.searchParams.set("cursor", cursor);
1649
1650 try {
1651 const apiResponse = await fetch(apiUrl.toString(), {
1652 headers: {
1653 Authorization: `Bearer ${apiKey}`,
1654 Accept: "application/json",
1655 },
1657 let responseData;
1658 try {
1659 responseData = await apiResponse.json();
1660 } catch (e) {
1661 const text = await apiResponse.text();
1662 console.error("Non-JSON response:", text);
1663 return Response.json(
1664 {
1665 status: "error",
1666 message: `API non-JSON response: ${apiResponse.statusText}`,
1667 },
1668 {
1669 status: apiResponse.status,
1670 }
1671 );
1672 }
1673 if (!apiResponse.ok || responseData.status === "error") {
1674 console.error(`API Error (${apiResponse.status}):`, responseData);
1675 return Response.json(
1676 {
1677 status: "error",
1678 message:
1679 responseData?.message || `API Error: ${apiResponse.statusText}`,
1680 },
1681 { status: apiResponse.status }
1682 );
1683 }

stevensDemosendDailyBrief.ts8 matches

@jasonhwestUpdated 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(

social_data_api_project3 file matches

@tsuchi_yaUpdated 16 hours ago

simple-scrabble-api1 file match

@bryUpdated 3 days ago
apiv1
papimark21