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=6&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 18895 results for "api"(2881ms)

chatExampleREADME.md5 matches

@laurynasUpdated 12 hours 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.

chatExamplequeries.ts2 matches

@laurynasUpdated 12 hours ago
7 queryKey: ["messages"],
8 queryFn: async () => {
9 const response = await fetch("/api/messages");
10 if (!response.ok) {
11 throw new Error("Failed to fetch messages");
25 return useMutation({
26 mutationFn: async (content: string) => {
27 const response = await fetch("/api/messages", {
28 method: "POST",
29 headers: { "Content-Type": "application/json" },

chatExampleindex.ts3 matches

@laurynasUpdated 12 hours ago
34app.get("/shared/**/*", c => serveFile(c.req.path, import.meta.url));
35
36// API endpoints
37app.get("/api/messages", async (c) => {
38 const messages = await getMessages();
39 return c.json(messages);
40});
41
42app.post("/api/messages", async (c) => {
43 const { content } = await c.req.json();
44

ValTownValsdk.ts3 matches

@wolfUpdated 13 hours ago
19 return true;
20 } catch (error) {
21 if (error instanceof ValTown.APIError && error.status === 404) {
22 return false;
23 }
61 return targetVal.id;
62 } catch (error) {
63 if (error instanceof ValTown.APIError) {
64 throw new Error(`Failed to resolve Val identifier: ${identifier}`);
65 }
217});
218
219export const sdk = new ValTown({ bearerToken: "VAL_TOWN_API_KEY_1" });

Loudaily_lineup_scheduler.tsx23 matches

@jeffvincentUpdated 13 hours ago
22}
23
24export interface YahooAPIConfig {
25 access_token: string;
26 refresh_token: string;
99 }
100
101 // Initialize Yahoo Fantasy API client
102 const yahooAPI = new YahooFantasyAPIClient(tokenData, this.tokenStorage, userId);
103
104 // Get user's leagues
105 const leagues = await yahooAPI.getUserLeagues(userId);
106 console.log(`🏟️ Found ${leagues.length} leagues for user ${userId}`);
107
111
112 // Get user's team in this league
113 const teamKey = await yahooAPI.getTeamKey(userId, league.league_id);
114 if (!teamKey) {
115 throw new Error(`Could not find team key for league ${league.league_id}`);
117
118 // Schedule pitchers for today
119 const scheduleResult = await this.schedulePitchersForTeam(yahooAPI, teamKey, date);
120
121 results.leagues_processed.push({
139 }
140
141 private async schedulePitchersForTeam(yahooAPI: YahooFantasyAPIClient, teamKey: string, date: Date) {
142 // Get today's probable pitchers from MLB API
143 const probablePitchers = await this.getTodaysProbablePitchers(date);
144 console.log(`🎯 Found ${probablePitchers.length} probable pitchers for ${date.toDateString()}`);
145
146 // Get current team roster
147 const roster = await yahooAPI.getTeamRoster(teamKey);
148 console.log(`👥 Team roster has ${roster.length} players`);
149
166 for (const change of optimization.changes) {
167 try {
168 await yahooAPI.setPlayerPosition(teamKey, change.playerId, change.newPosition);
169 results.pitchers_scheduled.push(change.playerId);
170 results.changes_made.push(change);
186 ): Promise<Array<{ name: string; team: string; game_time?: string }>> {
187 try {
188 // Call MLB Stats API for probable pitchers
189 const dateStr = date.toISOString().split("T")[0];
190 const response = await fetch(
191 `https://statsapi.mlb.com/api/v1/schedule?sportId=1&date=${dateStr}&hydrate=probablePitcher`,
192 );
193
194 if (!response.ok) {
195 throw new Error(`MLB API error: ${response.status}`);
196 }
197
399}
400
401// Simplified Yahoo Fantasy API client for Val.town
402class YahooFantasyAPIClient {
403 private config: YahooAPIConfig;
404 private baseUrl = "https://fantasysports.yahooapis.com/fantasy/v2";
405 private tokenStorage: LouTokenStorage;
406 private userId: string;
407
408 constructor(config: YahooAPIConfig, tokenStorage: LouTokenStorage, userId: string) {
409 this.config = config;
410 this.tokenStorage = tokenStorage;
424 private async refreshAccessToken(): Promise<void> {
425 try {
426 const response = await fetch("https://api.login.yahoo.com/oauth2/get_token", {
427 method: "POST",
428 headers: {
510
511 if (!retryResponse.ok) {
512 throw new Error(`Yahoo API error after refresh: ${retryResponse.status} ${retryResponse.statusText}`);
513 }
514
517
518 if (!response.ok) {
519 throw new Error(`Yahoo API error: ${response.status} ${response.statusText}`);
520 }
521
700
701 async setPlayerPosition(teamKey: string, playerId: string, position: string): Promise<void> {
702 // Yahoo Fantasy API requires PUT/POST for roster changes
703 const response = await fetch(`${this.baseUrl}/teams;team_keys=${teamKey}/roster/players;player_keys=${playerId}`, {
704 method: "PUT",
745
746 // Store results in Val.town's blob storage for history
747 await fetch("https://api.val.town/v1/blob/scheduler_results", {
748 method: "POST",
749 headers: {

saulyteindex.tsx10 matches

@laurynasUpdated 13 hours ago
175 await fetchWeatherData(locationData.lat, locationData.lon);
176 } else {
177 // Get location from API
178 const locationResponse = await fetch("/api/location");
179 const locationData = await locationResponse.json();
180 setLocation(locationData);
206 }
207
208 const response = await fetch(`/api/weather?lat=${lat}&lon=${lon}`);
209 const data = await response.json();
210
257 // Normalize the query for better search results
258 const normalizedQuery = query.trim();
259 const response = await fetch(`/api/geocode?q=${encodeURIComponent(normalizedQuery)}`);
260 const data = await response.json();
261
272 );
273
274 // Sort API results normally
275 const sortedApiResults = data.results.sort((a: GeocodingResult, b: GeocodingResult) => {
276 const aNameLower = a.name.toLowerCase();
277 const bNameLower = b.name.toLowerCase();
289 });
290
291 // Combine priority locations first, then API results (removing duplicates)
292 const allResults = [
293 ...matchingPriorityLocations,
294 ...sortedApiResults.filter(apiResult =>
295 !matchingPriorityLocations.some(priority =>
296 priority.name === apiResult.name && priority.country === apiResult.country
297 )
298 )
307 queryClient.prefetchQuery({
308 queryKey: ['weather', location.latitude, location.longitude],
309 queryFn: () => fetch(`/api/weather?lat=${location.latitude}&lon=${location.longitude}`).then(res => res.json()),
310 staleTime: 5 * 60 * 1000, // 5 minutes
311 });

saulyteCLAUDE.md13 matches

@laurynasUpdated 13 hours ago
14- **Routing**: TanStack Router for URL state management
15- **Styling**: CSS with responsive grid layouts
16- **Data Source**: Open-Meteo KNMI API (no API key required)
17
18## Project Structure
34- **Hono server** with error unwrapping for better debugging
35- **Static file serving** using Val Town utilities (`serveFile`, `readFile`)
36- **Three main API endpoints**:
37 - `/api/weather?lat={lat}&lon={lon}` - Weather data with photography insights
38 - `/api/location` - Auto-detect location from IP with Amsterdam fallback
39 - `/api/geocode?q={query}` - Search locations by city/area name
40- **Photography scoring algorithm** that calculates 1-10 ratings based on:
41 - Cloud cover percentage (main factor)
57### Core Data Flow
581. **Location Detection**: Auto-detect via IP or manual search/coordinates
592. **Weather Fetch**: Query Open-Meteo KNMI API with comprehensive hourly data
603. **Photography Analysis**: Generate insights with scoring algorithm
614. **UI Rendering**: Display in responsive grid with day/night distinction
145- Text files only (no binary uploads)
146- Serverless Deno environment
147- No Node.js APIs available
148- Cannot use `alert()`, `prompt()`, or `confirm()`
149- Use `return new Response(null, { status: 302, headers: { Location: "/path" }})` for redirects
158- **Error handling**: Let errors bubble up with context rather than catching/logging
159- **Never include secrets** in code - always use environment variables
160- **Prefer official SDKs** over writing API calls directly
161- **Comments**: Only explain complex logic, avoid commenting obvious operations
162- **Complete solutions**: Provide functional implementations, not skeleton code
174 ```
175
176## Data Sources and APIs
177
178- **Weather**: Open-Meteo KNMI API (free, no API key)
179- **Geocoding**: Open-Meteo Geocoding API (free, no API key)
180- **Location**: ip-api.com for IP-based location detection
181- **Fallback**: Amsterdam coordinates (52.3676, 4.9041) if detection fails
182
213```
214
215**Important**: These utilities ONLY run on the server. Pass data to client via HTML injection or API calls.
216
217## Testing and Deployment

firecrawlREADME.md1 match

@charmaineUpdated 13 hours ago
111. `Remix` this val
122. In `Environment Variables` on the val's left sidebar, put in your
13 `FIRECRAWL_API_KEY`
143. Click `Run` on `main.tsx`
154. See the website markdown in the logs below!

TowniePurchaseCreditsRoute.tsx2 matches

@valdottownUpdated 13 hours ago
15 const fetchBalance = async () => {
16 try {
17 const response = await fetch("/api/credit-balance");
18 if (response.ok) {
19 const data = await response.json();
35
36 try {
37 const response = await fetch("/api/purchase-credits", {
38 method: "POST",
39 headers: { "Content-Type": "application/json" },

tanstackReactHonoExampleREADME.md3 matches

@laurynasUpdated 13 hours ago
38```
39
40## API Endpoints
41
42- `GET /` - Serves the React application with initial data
43- `GET /api/messages` - Fetch all messages (JSON)
44- `POST /api/messages` - Create a new message
45- `GET /public/**` - Static assets (CSS, JS, etc.)
46- `/*` - All other routes handled by TanStack Router

shippingAPI1 file match

@dynamic_silverUpdated 10 hours ago

api_zenithpayments_com

@ianmenethilUpdated 20 hours ago
apiry
snartapi