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=149&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 11836 results for "api"(712ms)

twitterCardstweetCardTypes.ts21 matches

@nbbaier•Updated 2 weeks ago
14}
15
16export interface APIPhoto extends BaseMedia {
17 type: "photo";
18}
19
20export interface APIVideo extends BaseMedia {
21 type: "video" | "gif";
22 thumbnail_url: string;
24}
25
26export interface APIExternalMedia {
27 type: string;
28 url: string;
32}
33
34export interface APIMosaicPhotoFormats {
35 webp: string;
36 jpeg: string;
37}
38
39export interface APIMosaicPhoto {
40 type: "mosaic_photo";
41 width: number;
42 height: number;
43 formats: APIMosaicPhotoFormats;
44}
45
46export interface TweetMedia {
47 all?: APIVideo[];
48 external?: APIExternalMedia;
49 photos?: APIPhoto[];
50 videos?: APIVideo[];
51 mosaic?: APIMosaicPhoto;
52}
53
54export interface APIPollChoice {
55 label: string;
56 count: number;
58}
59
60export interface APIPoll {
61 choices: APIPollChoice[];
62 total_votes: number;
63 ends_at: string;
65}
66
67export interface APITranslate {
68 text: string;
69 source_lang: string;
71}
72
73export interface APIAuthor {
74 name: string;
75 screen_name: string;
79}
80
81export interface APITweet {
82 id: string;
83 url: string;
90 replying_to_status: string | null;
91 twitter_card: TwitterCardType;
92 author: APIAuthor;
93 source: string;
94
98 views: number | null;
99
100 quote?: APITweet;
101 poll?: APIPoll;
102 translation?: APITranslate;
103 media?: TweetMedia;
104}

utilitiesemptyValUtils.ts2 matches

@nbbaier•Updated 2 weeks ago
4export async function listEmptyVals(id: string) {
5 const token = Deno.env.get("valtown");
6 const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
7 headers: { Authorization: `Bearer ${token}` },
8 });
12export async function deleteEmptyVals(id: string) {
13 const token = Deno.env.get("valtown");
14 const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
15 headers: { Authorization: `Bearer ${token}` },
16 });

dbToAPI_backupexample.tsx2 matches

@nbbaier•Updated 2 weeks ago
1import { db } from "https://esm.town/v/nbbaier/dbToAPI_backup/lowdbTest.ts";
2import { createServer } from "https://esm.town/v/nbbaier/dbToAPI_backup/server.tsx";
3
4const app = await createServer(db);

dbToAPI_backupserver.tsx2 matches

@nbbaier•Updated 2 weeks ago
1/** @jsxImportSource https://esm.sh/hono@3.9.2/jsx **/
2
3import { Homepage } from "https://esm.town/v/nbbaier/dbToAPI_backup/frontend.tsx";
4import {
5 checkResource,
7 type Options,
8 validate,
9} from "https://esm.town/v/nbbaier/dbToAPI_backup/helpers.tsx";
10import { Hono } from "npm:hono";
11

dbToAPI_backupfrontend.tsx2 matches

@nbbaier•Updated 2 weeks ago
1// https://www.val.town/v/nbbaier/dbToAPIFrontend
2
3/** @jsxImportSource https://esm.sh/hono@3.9.2/jsx **/
25
26 <div class="space-y-2">
27 <p>You've set up an API for your Val Town lowdb instance</p>
28 <p>
29 ✧*。٩(ˊᗜˋ*)و✧*。

FarcasterMiniAppStoreHome.tsx2 matches

@moe•Updated 2 weeks ago
38function MiniApps() {
39 const { data: miniapps } = useQuery(["miniapps"], async () => {
40 // return await fetch(`/api/miniapps`).then(r => r.json()).then(r => r);
41 // return await fetchNeynarGet(`frame/catalog?limit=100`).then(r => r.frames);
42 return await fetchNeynarGetPages(`frame/catalog?limit=100`, 4, "frames").then(r => r.frames);
98 onChange={e => setSearch(e.target.value)}
99 placeholder="Search..."
100 autoCapitalize="on"
101 autoCorrect="on"
102 type="text"

perplexityAPImain.tsx4 matches

@nbbaier•Updated 2 weeks ago
1import { PplxRequest, PplxResponse } from "https://esm.town/v/nbbaier/perplexityAPI/pplxTypes.ts";
2import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON";
3
4export const pplx = async (options: PplxRequest & { apiKey?: string }): Promise<PplxResponse> => {
5 const token = options.apiKey ? options.apiKey : Deno.env.get("PERPLEXITY_API_KEY");
6 return await fetchJSON("https://api.perplexity.ai/chat/completions", {
7 method: "POST",
8 headers: {

testmain.tsx30 matches

@salon•Updated 2 weeks ago
15const InputSchema = z.object({
16 ticker: z.string().min(1).max(10).toUpperCase().trim().describe("Stock ticker symbol (e.g., AAPL)"),
17 alphaVantageKey: z.string().optional().describe("Alpha Vantage API Key (optional, uses cache if blank)"),
18 polygonKey: z.string().optional().describe("Polygon.io API Key (optional, uses cache if blank)"),
19});
20type Input = z.infer<typeof InputSchema>;
21
22// --- API Response Types (simplified) ---
23interface AlphaVantageTimeSeriesData {
24 "Time Series (Daily)": {
50// TODO: error handling: Handle potential SQLite errors during initialization
51sqlite.execute(
52 `CREATE TABLE IF NOT EXISTS api_cache (
53 key TEXT PRIMARY KEY,
54 value TEXT,
73 * @param cacheKey - Unique key for the cached data.
74 * @param fetchFn - Async function to fetch data if cache is invalid.
75 * @param apiKey - API key, used to determine if live fetch is possible.
76 * @param steps - Log array.
77 * @returns The fetched or cached data.
80 cacheKey: string,
81 fetchFn: () => Promise<T>,
82 apiKey: string | undefined | null,
83 steps: string[],
84): Promise<T | null> {
90 try {
91 const row = await sqlite.execute({
92 sql: `SELECT value, timestamp FROM api_cache WHERE key = ?`,
93 args: [cacheKey],
94 });
112 }
113
114 if (!apiKey) {
115 steps.push(`API key missing for ${cacheKey}, cannot fetch fresh data.`);
116 if (cachedData) {
117 steps.push(`Returning expired cached data for ${cacheKey} as fallback.`);
118 return cachedData; // Return stale data if no API key
119 }
120 steps.push(`No data available for ${cacheKey} (no API key and no valid/stale cache).`);
121 return null; // No API key and no cache (valid or stale)
122 }
123
130 try {
131 await sqlite.execute({
132 sql: `INSERT OR REPLACE INTO api_cache (key, value, timestamp) VALUES (?, ?, ?)`,
133 args: [cacheKey, JSON.stringify(freshData), newTimestamp],
134 });
152 * Fetches historical stock data from Alpha Vantage.
153 * @param ticker - Stock ticker symbol.
154 * @param apiKey - Alpha Vantage API key.
155 * @param steps - Log array.
156 * @returns Parsed Alpha Vantage time series data or null.
158async function fetchAlphaVantageData(
159 ticker: string,
160 apiKey: string | undefined | null,
161 steps: string[],
162): Promise<AlphaVantageTimeSeriesData | null> {
166 // TODO: error handling: Handle potential fetch errors (network, non-200 status)
167 const url =
168 `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${ticker}&outputsize=full&apikey=${apiKey}`;
169 const response = await fetch(url);
170 if (!response.ok) {
171 throw new Error(`Alpha Vantage API error: ${response.statusText} (Status: ${response.status})`);
172 }
173 const data = await response.json() as AlphaVantageTimeSeriesData;
175 if (!data || !data["Time Series (Daily)"]) {
176 if ((data as any)?.["Error Message"]) {
177 throw new Error(`Alpha Vantage API error: ${(data as any)["Error Message"]}`);
178 }
179 if ((data as any)?.["Information"]) {
180 throw new Error(`Alpha Vantage API info (potential rate limit): ${(data as any)["Information"]}`);
181 }
182 throw new Error("Invalid data structure received from Alpha Vantage.");
185 };
186
187 return getCachedData(cacheKey, fetchFn, apiKey, steps);
188}
189
191 * Fetches previous day's close price from Polygon.io.
192 * @param ticker - Stock ticker symbol.
193 * @param apiKey - Polygon.io API key.
194 * @param steps - Log array.
195 * @returns Parsed Polygon previous close data or null.
197async function fetchPolygonData(
198 ticker: string,
199 apiKey: string | undefined | null,
200 steps: string[],
201): Promise<PolygonPreviousCloseData | null> {
204 steps.push(`Workspaceing Polygon.io data for ${ticker}`);
205 // TODO: error handling: Handle potential fetch errors (network, non-200 status)
206 const url = `https://api.polygon.io/v2/aggs/ticker/${ticker}/prev?adjusted=true&apiKey=${apiKey}`;
207 const response = await fetch(url);
208 if (!response.ok) {
212 if (errorJson?.message) errorBody = errorJson.message;
213 } catch {}
214 throw new Error(`Polygon API error: ${response.statusText} (Status: ${response.status}) - ${errorBody}`);
215 }
216 const data = await response.json() as PolygonPreviousCloseData;
217 // TODO: error handling: Validate the structure of the returned data
218 if (data?.status === "ERROR") {
219 throw new Error(`Polygon API error: ${data?.request_id} - Check ticker or API key.`);
220 }
221 if (!data || !data.results || data.results.length === 0) {
225 };
226
227 return getCachedData(cacheKey, fetchFn, apiKey, steps);
228}
229
459 <body>
460 <h1>Stock Analyzer</h1>
461 <p>Enter a stock ticker and optionally your API keys. If keys are omitted, the tool will attempt to use cached data (up to 1 day old).</p>
462 <form id="stockForm">
463 <div>
554 console.log("Starting self-test...");
555 const testPayload: Input = {
556 ticker: "FAKE", // Use a fake ticker that likely won't hit real APIs if keys are absent
557 alphaVantageKey: "FAKE_AV_KEY", // Use fake keys
558 polygonKey: "FAKE_POLY_KEY",
559 };
560
561 // Mock fetch to avoid actual API calls and simulate responses
562 const originalFetch = global.fetch;
563 global.fetch = (url: string, options?: any): Promise<any> => {
610 // Clear cache for the fake ticker before running the test
611 await sqlite.execute({
612 sql: `DELETE FROM api_cache WHERE key = ? OR key = ?`,
613 args: [`alphavantage_${testPayload.ticker}`, `polygon_${testPayload.ticker}`],
614 });
the-juice

the-juicetragic-indigo-gopher1 match

@jxnblk•Updated 2 weeks ago
94 <head>
95 <meta charset="UTF-8">
96 <link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet">
97 <meta name="viewport" content="width=device-width, initial-scale=1.0">
98 <title>Hello World Val</title>

Futuremain.tsx7 matches

@salon•Updated 2 weeks ago
106 `You are a Stock Ticker Interpretation Agent. You are provided with calculated technical indicator values, volatility metrics, simulated news sentiment, and user goals for a SINGLE stock ticker. Your task is to interpret these quantitative signals and context, providing a qualitative summary focused on trend, momentum, volatility, and goal alignment. DO NOT PERFORM CALCULATIONS. Interpret the provided numbers. Input Data Description Example (JSON String): '{ "ticker": "AAPL", "userGoals": { "riskTolerance": "Medium", "timeHorizon": "Long-term (5+yr)", ... }, "metrics": { "lastClose": 171.80, "sma20": 170.50, "sma50": 168.00, "sma200": 160.00, "rsi14": 58.5, "macdLine": 1.2, "signalLine": 1.0, "histogram": 0.2, "bollingerBands": { "upper": 175.00, "middle": 170.50, "lower": 166.00 }, "atr14": 2.5, "historicalVolatility": 0.28 }, "context": { "newsSentiment": "Neutral" } }' Interpretation Focus: - Trend: Based on price relative to SMAs (e.g., price > SMA50 > SMA200 suggests uptrend). - Momentum: Based on RSI (e.g., >70 overbought, <30 oversold, 50 neutral), MACD (e.g., MACD line > signal line bullish, histogram > 0 bullish momentum). - Volatility: Based on ATR/Historical Volatility (comment if high/medium/low for this stock type) and Bollinger Bands (price near upper/lower bands?). - Signal Confluence: Do indicators generally agree (e.g., price above MAs, RSI rising, MACD bullish)? Or are signals mixed? - News Context: Does sentiment support or contradict the technical picture? - Goal Alignment: Briefly comment on how the stock's current state (trend, volatility) aligns with the user's risk/horizon. Respond ONLY in JSON format matching the TickerInterpretation interface (keys: ticker, summary, indicatorInterpretation, volatilityAssessment, alignmentWithGoals, confidence, newsContextSentiment). Confidence should reflect the clarity and confluence of signals (High if most indicators agree, Low if mixed/unclear). If interpretation cannot be done due to missing metrics, return JSON with "ticker" and "error". Example JSON Response (Success): { "ticker": "AAPL", "summary": "AAPL shows indicators suggesting a moderate short-term uptrend (Price > SMA20/50) with neutral to slightly positive momentum (RSI near 60, MACD mildly bullish). Volatility is moderate.", "indicatorInterpretation": "Price is above key short and medium-term moving averages (SMA20, SMA50), indicating positive trend. RSI at 58.5 shows neutral momentum, not overbought. MACD confirms slight bullish momentum (line>signal, histogram positive). Price is within the Bollinger Bands, suggesting non-extreme movement currently.", "volatilityAssessment": "ATR and historical volatility suggest moderate volatility typical for a large-cap tech stock. Not excessively erratic based on recent data.", "alignmentWithGoals": "The current stable uptrend aligns with a Medium risk tolerance and Long-term horizon. Fits Technology sector interest.", "confidence": "Medium", "newsContextSentiment": "Neutral" } Example JSON Response (Error): { "ticker": "XYZ", "error": "Insufficient metrics provided for meaningful interpretation (e.g., missing MAs or RSI)." }`;
107const synthesisChartingDataAgentSystemPrompt =
108 `You are a Synthesis Agent. You receive User Goals, a list of Ticker Interpretations (based on calculated metrics & sentiment), and Ticker Predictions (multiple simulated future price paths based on volatility). Your task is to: 1. Synthesize a coherent overall outlook. 2. Provide CONCRETE, ACTIONABLE next steps for each ticker and potentially the portfolio, tailored to user goals. **Crucially, rationale MUST consider BOTH the interpretation (trend, momentum) AND the prediction scenarios (range of outcomes, uncertainty).** Frame suggestions carefully (e.g., "Consider...", "Given the predicted range...", "Monitor for break above predicted resistance..."). 3. Identify Key Risks, explicitly including the uncertainty shown in the prediction ranges. 4. Identify Key Opportunities. 5. Include a standard disclaimer about prediction uncertainty and not being financial advice. DO NOT GIVE FINANCIAL ADVICE. Acknowledge tickers where interpretation/prediction failed. Input Example (JSON String): '{ "userGoals": { "riskTolerance": "Medium", "timeHorizon": "Long-term (5+yr)", "investmentAmount": 10000 }, "tickerInterpretations": [ { "ticker": "AAPL", "summary": "Moderate uptrend, neutral momentum...", "indicatorInterpretation": "Price > MAs...", "volatilityAssessment": "Moderate", "alignmentWithGoals": "Fits goals", "confidence": "Medium", "newsContextSentiment": "Neutral" }, { "ticker": "MSFT", "summary": "Strong uptrend, strong momentum...", "confidence": "High", ... } { "ticker": "NVDA", "error": "Interpretation failed due to missing metrics." } ], "tickerPredictions": [ { "ticker": "AAPL", "predictionPaths": [ [{date:"...", price:175}, ...], ... ], "predictionPeriodDays": 60 }, { "ticker": "MSFT", "predictionPaths": [ ... ], "predictionPeriodDays": 60 }, { "ticker": "NVDA", "error": "Prediction failed." } ], "pastPerformanceContext": "Past suggestions showed moderate gains but higher volatility than expected." }' Focus on: - Synthesis: Combine interpretation (current state) with prediction (potential futures). - Prediction Integration: Acknowledge the range/median/risk suggested by the simulation paths in rationale and risks. - Goal Alignment: How do findings + predictions fit risk/horizon? - Actionability: Clear steps. Consider allocation if amount provided. Handle failed analyses/predictions appropriately. - Risk Management: Highlight risks from interpretations AND prediction uncertainty/range. - Disclaimer: Include the standard disclaimer text. Respond ONLY in JSON format matching the EnhancedActionSynthesis interface (keys: overallOutlook, actionableSteps [list], keyRisks, keyOpportunities, disclaimer). ChartData is handled separately by code. If synthesis fails, return JSON with "error". Example JSON Response: { "overallOutlook": "Based on interpretations and predictive simulations, the outlook is mixed. MSFT shows strong current signals and favorable prediction scenarios, aligning well with goals despite needing volatility monitoring (per past context). AAPL shows a less decisive trend, reflected in a wider prediction range, suggesting a more cautious approach. NVDA analysis was incomplete. Overall strategy should account for prediction uncertainty.", "actionableSteps": [ { "ticker": "MSFT", "action": "Consider Allocation", "rationale": "Strong technical interpretation (uptrend, momentum) supported by predictions showing predominantly positive outcomes, although a -5% path exists. Fits Medium risk/Long-term goals. Consider starting/adding, but monitor volatility given past context and the inherent uncertainty in predictions.", "confidence": "High" }, { "ticker": "AAPL", "action": "Watch", "rationale": "Interpretation shows consolidation within an uptrend. Predictions show a wide range (-10% to +15%), indicating uncertainty. Suggest waiting for a clearer breakout or confirmation, aligning interpretation with a favorable prediction path before committing capital.", "confidence": "Medium" }, { "ticker": "NVDA", "action": "Further Research", "rationale": "Interpretation and prediction failed due to data/metric issues. Cannot assess suitability without further investigation.", "confidence": "Low" }, { "ticker": "Portfolio", "action": "Consider Allocation", "rationale": "With $10,000, diversifying across 2-3 positions (like MSFT and potentially AAPL later) seems appropriate for Medium risk. The prediction ranges suggest potential drawdowns, so position sizing should be cautious.", "confidence": "Medium" } ], "keyRisks": [ "Market-wide pullbacks impacting tech.", "Prediction uncertainty: Actual outcomes can fall outside simulated ranges for MSFT & AAPL.", "Volatility may exceed expectations (past context).", "Incomplete analysis for NVDA.", "AAPL's consolidation resolving downwards, potentially hitting lower end of prediction range." ], "keyOpportunities": [ "Capturing potential upside shown in favorable prediction paths (esp. MSFT).", "Entering AAPL if positive confirmation aligns interpretation and predictions.", "Diversification benefits." ], "disclaimer": "IMPORTANT: Stock market predictions are inherently uncertain and based on simplified models (Monte Carlo simulations of past volatility). These simulations are illustrative, not guarantees of future performance. Actual results may vary significantly. This analysis is for informational purposes only and does NOT constitute financial advice. Consult with a qualified financial advisor before making investment decisions." }`;
109
110function generateHtmlShell(initialAnalysisResult: string | null): string {
305 var analysisRes;
306 try {
307  var apiUrl = window.location.pathname + '?action=analyze_goals&format=json';
308  var res = await fetch(apiUrl, {
309   method: 'POST',
310   headers: { 'Content-Type': 'application/json', },
398  else if (err.message) { errMsg += ` Details: ${err.message}`; }
399  else { try { errMsg += ` Unknown err: ${JSON.stringify(errData)}`; } catch { errMsg += " Unknown non-serializable err."; }}
400  if (code === 401) errMsg += " (ACTION: Check API key)";
401  else if (code === 429) errMsg += " (ACTION: Rate limit/quota exceeded)";
402  else if (code === 400) errMsg += " (ACTION: Bad request/prompt issue)";
474  if (jsonData?.chart?.error) {
475   const errDesc = jsonData.chart.error.description || jsonData.chart.error.code || "Unknown Yahoo error";
476   internalLog(`${logPfx}: [ERROR] Yahoo API Error: ${errDesc}`);
477   return { ticker, error: `Yahoo API Error: ${errDesc}`, dates: [], open: [], high: [], low: [], close: [], volume: [] };
478  }
479  if (!res.ok || !jsonData?.chart?.result?.[0]) {
1412 const action = url.searchParams.get("action");
1413 if (format === "json" && action === "analyze_goals" && req.method === "POST") {
1414  log("INFO", "Handler", `API Request Received: ${req.method} ${url.pathname}${url.search}`);
1415  let userGoals: UserGoals;
1416  try {

simple-scrabble-api1 file match

@bry•Updated 5 hours ago

social_data_api_project3 file matches

@tsuchi_ya•Updated 13 hours ago
mux
Your friendly, neighborhood video API.
api