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/$%7Burl%7D?q=api&page=78&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 12426 results for "api"(1289ms)

stevensDemoApp.tsx8 matches

@cdukeUpdated 1 week 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;

HHGtoMyDaygenerateFunFacts.ts5 matches

@lm3mUpdated 1 week 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

HHGtoMyDaygetWeather.ts5 matches

@lm3mUpdated 1 week ago
23async function generateConciseWeatherSummary(weatherDay) {
24 try {
25 // Get API key from environment
26 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
27 if (!apiKey) {
28 console.error("Anthropic API key is not configured.");
29 return null;
30 }
31
32 // Initialize Anthropic client
33 const anthropic = new Anthropic({ apiKey });
34
35 const response = await anthropic.messages.create({
7import { sqlite } from "https://esm.town/v/std/sqlite";
8
9// Discord API endpoints
10const API_BASE = "https://discord.com/api/v10";
11
12// Initialize the Discord rate limit service
47}
48
49// Enhanced Discord API request with rate limiting
50async function discordRequest(endpoint: string, options: RequestInit = {}) {
51 const token = Deno.env.get("DISCORD_BOT_TOKEN");
54 }
55
56 const url = `${API_BASE}${endpoint}`;
57 const headers = {
58 "Authorization": `Bot ${token}`,
84 }
85
86 console.error(`❌ Discord API error: ${response.status}`, errorBody);
87 throw new Error(`Discord API error: ${response.status} ${JSON.stringify(errorBody)}`);
88 }
89
189 const routeKey = `/channels/${channelId}/messages`;
190
191 // Discord API has a limit of 100 messages per request, so we need to paginate
192 while (hasMore) {
193 const endpoint = lastId
204 lastId = messages[messages.length - 1].id;
205
206 // If we've gotten more than 1000 messages, stop to avoid excessive API calls
207 if (allMessages.length >= 1000) {
208 console.log("Reached 1000 message limit, stopping pagination");
236}
237
238// Get user info from Discord API with rate limiting
239async function getUserInfo(guildId: string, userId: string) {
240 try {
16 }
17
18 const url = `https://discord.com/api/v10${endpoint}`;
19 const headers = {
20 "Authorization": `Bot ${token}`,
34
35 if (!response.ok) {
36 console.error(`❌ Discord API error: ${response.status}`);
37 throw new Error(`Discord API error: ${response.status}`);
38 }
39
1// discord-rate-limit-service.ts - Advanced rate limiting for Discord API with
2// exponential backoff, circuit breaker, global rate limit handling, and blob persistence
3
14}
15
16// API call tracking for global rate limits
17interface ApiCallRecord {
18 timestamp: number;
19}
33 private static instance: DiscordRateLimitService;
34 private rateLimitBuckets: Map<string, RateLimitInfo> = new Map();
35 private apiCallTimes: ApiCallRecord[] = [];
36 private globalLock: boolean = false;
37
217 console.log(`⚡ Circuit breaker open, blocking requests for ${waitTime} more seconds`);
218 throw new Error(
219 `Circuit breaker open. API requests blocked for ${waitTime} more seconds due to too many failures.`,
220 );
221 }
263 }
264
265 // Main method to execute API calls with rate limiting
266 public async executeWithRateLimit<T>(
267 routeKey: string,
289 await this.ensureDynamicRateLimitCompliance(routeKey);
290
291 // Execute the actual API call
292 const result = await action();
293
401 // Check for Discord's global rate limit message
402 if (error.message && typeof error.message === "string") {
403 if (error.message.includes("You are being blocked from accessing our API temporarily")) {
404 // Set a longer global rate limit time (e.g., 10 minutes)
405 this.globalRateLimitUntil = Date.now() + 10 * 60 * 1000;
567
568 // Also track for global rate limiting
569 this.trackApiCall();
570 }
571
572 // Track an API call for global rate limiting
573 private trackApiCall(): void {
574 const now = Date.now();
575 this.apiCallTimes.push({ timestamp: now });
576
577 // Clean up old records
578 this.apiCallTimes = this.apiCallTimes.filter(call => now - call.timestamp <= this.RATE_LIMIT_WINDOW_MS);
579 }
580
651
652 // Clean up old records
653 this.apiCallTimes = this.apiCallTimes.filter(call => now - call.timestamp <= this.RATE_LIMIT_WINDOW_MS);
654
655 // If we have capacity, return immediately
656 if (this.apiCallTimes.length < this.RATE_LIMIT_PER_SECOND) {
657 return;
658 }
659
660 // Calculate how long to wait before making another request
661 if (this.apiCallTimes.length > 0) {
662 // Get the oldest API call in our window
663 const oldestCall = this.apiCallTimes[0];
664
665 // Calculate when that call will expire from our window
luciaMagicLinkStarter

luciaMagicLinkStarterindex.ts2 matches

@stevekrouseUpdated 1 week ago
15app.get("/frontend/**/*", c => serveFile(c.req.path, import.meta.url));
16
17// Add your API routes here
18// app.get("/api/data", c => c.json({ hello: "world" }));
19
20// Unwrap and rethrow Hono errors as the original error
19import type {
20 HellLetLooseMapData,
21 MapInfo,
22} from "https://esm.town/v/ktodaz/Discord_Bot_Services/map_vote/map-vote-getHellLetLooseMapData.tsx";
23
24import type { CurrentConfig } from "https://esm.town/v/ktodaz/Discord_Bot_Services/map_vote/map-vote-getCurrentConfig.tsx";
25
26// Discord API endpoints
27const API_BASE = "https://discord.com/api/v10";
28
29// Initialize the Discord rate limit service
44};
45
46// Enhanced Discord API request function with rate limiting
47async function discordRequest(endpoint: string, options: RequestInit = {}) {
48 const token = Deno.env.get("DISCORD_BOT_TOKEN");
51 }
52
53 const url = `${API_BASE}${endpoint}`;
54 const headers = {
55 "Authorization": `Bot ${token}`,
82 }
83
84 console.error(`❌ Discord API error: ${response.status}`, errorBody);
85 throw new Error(`Discord API error: ${response.status} ${JSON.stringify(errorBody)}`);
86 }
87
106
107 return rateLimitService.executeWithRateLimit(routeKey, async () => {
108 const url = `${API_BASE}/channels/${channelId}/messages/${messageId}/reactions/${emoji}/@me`;
109 const token = Deno.env.get("DISCORD_BOT_TOKEN");
110
237 title: initialEmbedData.InitialEmbedTitle || "Loading . . .",
238 description: initialEmbedData.InitialEmbedDescription
239 || "Due to Discord API rate limits this will take a few minutes.",
240 fields: [
241 {
272
273// Process variants for a map and add emoji reactions
274async function processMapVariants(messageId: string, channelId: string, map: MapInfo, variantOptions: any) {
275 const mapMetaVariants: string[] = [];
276 const mapEnabledVariants: string[] = [];

crypto-geminiscript.tsx18 matches

@hexmanshuUpdated 1 week ago
1// Val Town Backend: cryptoDataEndpoint.tsx
2// Make sure to set the COINGECKO_API_KEY environment variable in Val Town
3
4import { fetch } from "npm:undici"; // Use undici for fetch in Node.js environment
50}
51
52const COINGECKO_API_KEY = Deno.env.get("COINGECKO_API_KEY");
53const COINGECKO_API_BASE = COINGECKO_API_KEY
54 ? "https://pro-api.coingecko.com/api/v3"
55 : "https://api.coingecko.com/api/v3";
56
57const FNG_API_URL = "https://api.alternative.me/fng/?limit=1";
58
59async function fetchFromApi<T>(url: string, isCoinGecko: boolean = true): Promise<T | null> {
60 const headers: HeadersInit = {};
61 if (isCoinGecko && COINGECKO_API_KEY) {
62 headers["x-cg-pro-api-key"] = COINGECKO_API_KEY;
63 // or "x-cg-demo-api-key" if that's the header for your key
64 }
65
68 if (!response.ok) {
69 const errorText = await response.text();
70 console.error(`API Error for ${url}: ${response.status} ${response.statusText}`, errorText);
71 return null;
72 }
100 topCoinsData,
101 ] = await Promise.all([
102 fetchFromApi<CoinGeckoMarketCoin[]>(`${COINGECKO_API_BASE}/coins/markets?vs_currency=usd&ids=bitcoin`),
103 fetchFromApi<CoinGeckoChartData>(
104 `${COINGECKO_API_BASE}/coins/bitcoin/market_chart?vs_currency=usd&days=30&interval=daily`,
105 ),
106 fetchFromApi<FearAndGreedData>(FNG_API_URL, false), // false for isCoinGecko
107 fetchFromApi<CoinGeckoGlobalData>(`${COINGECKO_API_BASE}/global`),
108 fetchFromApi<CoinGeckoMarketCoin[]>(
109 `${COINGECKO_API_BASE}/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10&page=1&sparkline=true&price_change_percentage=7d`,
110 ),
111 ]);
1export interface MapInfo {
2 MapName: string;
3 MapDetails: MapDetails;
20
21export interface HellLetLooseMapData {
22 Maps: MapInfo[];
23}
24

vapi-minutes-db2 file matches

@henrywilliamsUpdated 51 mins ago

social_data_api_project3 file matches

@tsuchi_yaUpdated 2 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