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//%22https:/cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css/%22?q=api&page=1&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 25401 results for "api"(1005ms)

spotymain.ts2 matches

@skirtownerUpdated 1 hour ago
19 const now = Date.now();
20 if (!cached.accessToken || now >= cached.expiresAt) {
21 const tokenResp = await fetch("https://accounts.spotify.com/api/token", {
22 method: "POST",
23 headers: {
46 let playlists: any[] = [];
47 let nextUrl: string | null =
48 "https://api.spotify.com/v1/me/playlists?limit=50";
49
50 while (nextUrl) {
1# API Routes
2
3JSON API endpoints for frontend/backend communication.
4
5## Separation of Concerns
6
7API routes handle:
8- JSON request/response formatting
9- HTTP status code management
11- Error response standardization
12
13API routes delegate business logic to controllers and return clean JSON responses.
14
15## Endpoints
16
17### GET /api/health
18
19**Purpose**: System health check endpoint
32**HTTP Status**: Always 200
33
34### POST /api/viewing
35
36**Purpose**: Update page viewing status in blob storage for real-time tracking with immediate Notion sync
41 pageId: string, // Notion page UUID
42 viewing: boolean, // true when actively viewing, false when leaving
43 tabVisible: boolean // Page Visibility API state
44}
45```
92```
93
94### GET /api/viewing/:id
95
96**Purpose**: Get current viewing status for a page
125**Error Responses**: Same pattern as other endpoints
126
127### GET /api/viewing/:id/stats
128
129**Purpose**: Get viewing analytics/statistics for a page
148```
149
150### GET /api/demo/:id/properties
151
152**Purpose**: Get Notion page properties (filtered for UI consumption)
198{
199 error: "Failed to fetch page data",
200 details: "Notion API error message"
201}
202```
203
204### GET /api/demo/:id
205
206**Purpose**: Get complete Notion page with content blocks
251## Error Handling Pattern
252
253All API routes follow consistent error handling:
254
255```typescript
269## Data Filtering
270
271API routes return filtered data for UI consumption:
272- **Button properties removed**: Notion button properties are filtered out to prevent UI confusion
273- **Raw Notion format**: Other properties maintain their original Notion API structure
274- **Complete hierarchy**: Block content includes full nested structure with children
275
278```bash
279# Get page properties only
280curl https://your-val.web.val.run/api/demo/abc123/properties
281
282# Get complete page with content
283curl https://your-val.web.val.run/api/demo/abc123
284
285# Health check
286curl https://your-val.web.val.run/api/health
287```
9// Simple test endpoint
10app.get("/test", async (c) => {
11 return c.json({ message: "API routes working", timestamp: new Date().toISOString() });
12});
13
131 const { cleanupStaleViewingSessions } = await import("../../controllers/viewing.controller.ts");
132
133 console.log("🔧 Manual cleanup triggered via API");
134 const result = await cleanupStaleViewingSessions();
135
16
17 const updateStatus = async (viewing: boolean, tabVisible: boolean) => {
18 // Only make API calls if user is authorized
19 if (!isAuthorized) {
20 console.log("User not authorized for viewing analytics on this page");
71
72 try {
73 navigator.sendBeacon('/api/viewing', JSON.stringify(payload));
74 } catch (err) {
75 // Fallback to synchronous fetch if sendBeacon fails
76 console.warn("sendBeacon failed, attempting synchronous request:", err);
77 try {
78 fetch('/api/viewing', {
79 method: 'POST',
80 headers: { 'Content-Type': 'application/json' },
67
68**Session Tracking:**
69- Uses `sendBeacon` API for reliable session ending during page unload
70- Falls back to synchronous fetch if sendBeacon fails
71- Handles both normal component unmount and browser tab closure

eventsCalendarserver.ts6 matches

@roopUpdated 3 hours ago
13
14import { Hono } from "npm:hono@4";
15import { SSEStreamingApi, stream, streamSSE } from "npm:hono@4/streaming";
16import { html, raw } from "npm:hono@4/html";
17import process from "node:process";
27 return streamSSE(c, async (stream) => {
28 // validate token
29 const apiToken = c.req.query("token");
30 if (apiToken !== process.env.API_TOKEN) {
31 await fail(stream, "Unauthorized");
32 return stream.close();
209});
210
211function update(stream: SSEStreamingApi, payload: any) {
212 return stream.writeSSE({
213 event: "update",
220
221function complete(
222 stream: SSEStreamingApi,
223 state: "success" | "error",
224) {
233
234function fail(
235 stream: SSEStreamingApi,
236 message?: string,
237) {

eventsCalendarlogs.tsx1 match

@roopUpdated 3 hours ago
20export const dashboard = async (req) => {
21 const token = new URL(req.url).searchParams.get("token");
22 if (token !== process.env.API_TOKEN) {
23 return new Response("Token required to view logs", { status: 403 });
24 }

TopTenVideosREADME.md2 matches

@pmapowerUpdated 4 hours ago
80```
81https://yoursite.com/custom-header.html
82https://api.yoursite.com/generate-header
83https://cdn.example.com/headers/analysis.html
84```
146- **Safe External Links**: `noopener noreferrer` attributes
147- **Input Validation**: URL validation for all inputs
148- **XSS Protection**: Proper HTML escaping
149- **Error Boundaries**: Graceful error handling
150

TopTenVideosindex.html2 matches

@pmapowerUpdated 4 hours ago
674 });
675
676 // Here you could make an API call to your backend
677 console.log('Selected niche data:', {
678 niche,
767 `;
768
769 // Sample video data (you can replace this with real API data)
770 const sampleVideos = [
771 {

TopTenVideosindex.html30 matches

@pmapowerUpdated 4 hours ago
90 <!-- Setup Instructions -->
91 <div id="setup-info" class="max-w-4xl mx-auto mt-12 bg-blue-50 border border-blue-200 rounded-lg p-6">
92 <h3 class="text-lg font-semibold text-blue-800 mb-3">🔧 YouTube API Setup Guide</h3>
93
94 <!-- API Key Tester -->
95 <div class="mb-6 bg-white p-4 rounded-lg border">
96 <h4 class="font-semibold text-gray-800 mb-3">🧪 Test Your API Key</h4>
97 <div class="flex gap-3">
98 <input
99 type="text"
100 id="test-api-key"
101 placeholder="Paste your YouTube API key here to test it..."
102 class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm font-mono"
103 >
113
114 <div class="mb-6">
115 <h4 class="font-semibold text-blue-800 mb-2">Step 1: Create API Key</h4>
116 <ol class="list-decimal list-inside text-blue-700 space-y-1 mb-4 ml-4">
117 <li>Go to <a href="https://console.developers.google.com/" target="_blank" class="underline font-medium">Google Cloud Console</a></li>
118 <li>Create a new project or select an existing one</li>
119 <li>Go to "APIs & Services" → "Library"</li>
120 <li>Search for and enable <strong>"YouTube Data API v3"</strong></li>
121 <li>Go to "APIs & Services" → "Credentials"</li>
122 <li>Click "Create Credentials" → "API Key"</li>
123 <li>Copy your API key</li>
124 </ol>
125 </div>
126
127 <div class="mb-6">
128 <h4 class="font-semibold text-blue-800 mb-2">Step 2: Configure API Key</h4>
129 <ol class="list-decimal list-inside text-blue-700 space-y-1 mb-4 ml-4">
130 <li>In Val Town, go to your environment variables</li>
131 <li>Add a new variable named: <code class="bg-blue-100 px-2 py-1 rounded font-mono">YOUTUBE_API_KEY</code></li>
132 <li>Paste your API key as the value</li>
133 <li>Save the environment variable</li>
134 </ol>
139 <div class="space-y-3 text-sm">
140 <div class="bg-white p-3 rounded border-l-4 border-yellow-400">
141 <strong class="text-gray-800">API Key Invalid Error:</strong>
142 <ul class="mt-1 text-gray-700 list-disc list-inside ml-4">
143 <li>Double-check your API key is copied correctly (no extra spaces)</li>
144 <li>Ensure YouTube Data API v3 is enabled in Google Cloud Console</li>
145 <li>Wait a few minutes after creating the key for it to activate</li>
146 <li>Try removing all API restrictions temporarily</li>
147 </ul>
148 </div>
150 <strong class="text-gray-800">Quota Exceeded Error:</strong>
151 <ul class="mt-1 text-gray-700 list-disc list-inside ml-4">
152 <li>YouTube API has daily quotas (10,000 units/day for free tier)</li>
153 <li>Each search uses ~100 units, so you can do ~100 searches per day</li>
154 <li>Reset happens at midnight Pacific Time</li>
159
160 <p class="text-sm text-blue-600">
161 💡 <strong>Good news:</strong> The YouTube Data API is completely free for personal use with generous daily quotas!
162 </p>
163 </div>
185
186 async handleTestKey() {
187 const testKeyInput = document.getElementById('test-api-key');
188 const testKeyBtn = document.getElementById('test-key-btn');
189 const resultDiv = document.getElementById('key-test-result');
190 const apiKey = testKeyInput.value.trim();
191
192 if (!apiKey) {
193 this.showKeyTestResult('Please enter an API key to test', 'error');
194 return;
195 }
198 testKeyBtn.textContent = 'Testing...';
199 resultDiv.className = 'mt-3 p-3 bg-gray-100 rounded text-sm';
200 resultDiv.innerHTML = '🔄 Testing API key...';
201 resultDiv.classList.remove('hidden');
202
203 try {
204 const response = await fetch('/api/test-key', {
205 method: 'POST',
206 headers: { 'Content-Type': 'application/json' },
207 body: JSON.stringify({ apiKey })
208 });
209 const data = await response.json();
210
211 if (data.success) {
212 this.showKeyTestResult(`✅ API key is valid! Found ${data.sampleData.videoCount} video(s).`, 'success');
213 } else {
214 this.showKeyTestResult(`❌ API key failed: ${data.error}`, 'error');
215 }
216 } catch (error) {
250
251 try {
252 const response = await fetch(`/api/videos?niche=${encodeURIComponent(niche)}`);
253 const data = await response.json();
254

PixelPixelApiMonitor1 file match

@selfire1Updated 6 hours ago
Regularly polls the API and messages on an error.

weatherApp1 file match

@dcm31Updated 12 hours ago
A simple weather app with dropdown cities using Open-Meteo API
fapian
<("<) <(")> (>")>
Kapil01