• Townie
    AI
  • Blog
  • Docs
  • Pricing
  • We’re hiring!
Log inSign up
greasegum

greasegum

birdfacts

Public
Like
birdfacts
Home
Code
7
backend
2
cron
1
frontend
1
README.md
test-facts.ts
test-llm.ts
test.ts
Branches
1
Pull requests
Remixes
History
Environment variables
3
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
Sign up now
Code
/
Code
/
Search
index.ts
https://greasegum--47620ec654ae11f088f8f69ea79377d9.web.val.run
README.md

Bird Facts Microservice

A robust, layered bird facts API that provides regionally-relevant bird information with fun facts and rich descriptions.

🌟 Features

  • Regional Bird Selection: Uses eBird API to get locally relevant birds
  • Fun Facts: API Ninjas for engaging bird facts
  • Rich Descriptions: Wikipedia API for detailed information and images
  • Smart Caching: Reduces API calls and improves response times
  • Graceful Fallbacks: Multiple data sources ensure reliable responses
  • Interactive Frontend: Beautiful web interface for testing and exploration
  • 🤖 AI-Powered Fact Curation: DeepSeek LLM filters and enhances facts for maximum fascination
  • Superlative Quality Scoring: Facts rated 1-10 for amazement factor
  • Enhanced Fact Rewriting: AI improves clarity and impact of bird facts

🚀 Live Demo

Visit the API at: https://your-val-url.web.val.run

📡 API Endpoints

Bird Information Endpoints

GET /api/birds/random

Get a random bird fact with regional relevance.

Query Parameters:

  • region (optional): Region code (e.g., "US-CA" for California)
  • lat (optional): Latitude for location-based results
  • lng (optional): Longitude for location-based results

Example Requests:

# Random bird from anywhere GET /api/birds/random # Birds from California GET /api/birds/random?region=US-CA # Birds near San Francisco GET /api/birds/random?lat=37.7749&lng=-122.4194

GET /api/birds/region/:regionCode

Get birds observed in a specific region.

GET /api/birds/species/:name

Get information for a specific bird species.

Quick Facts Endpoints (Pre-collected)

GET /api/facts/random

Get random structured facts from the pre-collected database (fast response).

Query Parameters:

  • count (optional): Number of facts to return (1-10, default: 1)
  • category (optional): Filter by category (behavior, appearance, habitat, diet, reproduction, migration, general)
  • region (optional): Filter by region code

Example Requests:

# Get 5 random facts GET /api/facts/random?count=5 # Get behavior facts from California GET /api/facts/random?count=3&category=behavior&region=US-CA # Get migration facts GET /api/facts/random?category=migration

Response:

{ "facts": [ { "id": "abc123", "name": "American Robin", "scientificName": "Turdus migratorius", "fact": "American robins are known for their distinctive red breast...", "category": "appearance", "source": "wikipedia", "region": "US-CA", "imageUrl": "https://upload.wikimedia.org/...", "wikipediaUrl": "https://en.wikipedia.org/wiki/American_robin", "collectedAt": "2025-06-29T06:00:00.000Z", "tags": ["american robin", "colorful", "common"] } ], "count": 1, "filters": { "category": "appearance", "region": "US-CA" } }

Superlative Facts Endpoints (AI-Curated)

GET /api/facts/superlative

Get AI-curated superlative facts with quality scoring.

Query Parameters:

  • count (optional): Number of facts to return (1-50, default: 10)
  • minQuality (optional): Minimum quality score (1-10, default: 7)
  • category (optional): Filter by category
  • uniqueness (optional): Filter by uniqueness level (interesting, extraordinary)

Example Requests:

# Get 10 highest quality facts GET /api/facts/superlative?minQuality=8 # Get extraordinary behavior facts GET /api/facts/superlative?category=behavior&uniqueness=extraordinary # Get top 20 superlative facts GET /api/facts/superlative?count=20&minQuality=9

Response:

{ "facts": [ { "originalFact": "The original fact text", "enhancedFact": "AI-enhanced version with better clarity and impact", "birdName": "Arctic Tern", "scientificName": "Sterna paradisaea", "qualityScore": 9.2, "superlativeAspects": ["record-breaking migration", "extreme endurance"], "reasoning": "This fact represents the longest migration in the animal kingdom...", "category": "behavior", "emotionalImpact": "high", "uniqueness": "extraordinary", "filteredAt": "2025-06-29T06:00:00.000Z", "region": "Arctic", "imageUrl": "https://upload.wikimedia.org/...", "wikipediaUrl": "https://en.wikipedia.org/wiki/Arctic_tern" } ], "count": 1, "filters": { "minQuality": 8, "category": "all", "uniqueness": "all" } }

GET /api/facts/superlative/top

Get the top superlative facts with an AI-generated nature documentary summary.

Query Parameters:

  • count (optional): Number of top facts to return (default: 20)

Response:

{ "facts": [...], // Array of top superlative facts "summary": "In the vast tapestry of avian evolution, these remarkable creatures showcase nature's most extraordinary innovations...", "count": 20 }

GET /api/facts/superlative/stats

Get comprehensive statistics about the AI-curated superlative facts collection.

Response:

{ "totalFacts": 156, "averageQuality": 8.3, "lastUpdated": "2025-06-29T06:00:00.000Z", "topCategories": { "behavior": 45, "physiology": 32, "ecology": 28, ... }, "qualityDistribution": { "9-10": 23, "8-9": 67, "7-8": 66 }, "topBirds": [ { "name": "Arctic Tern", "count": 3, "avgQuality": 9.1 } ] }

GET /api/facts/stats

Get statistics about the facts collection.

Response:

{ "totalFacts": 847, "lastUpdated": "2025-06-29T06:00:00.000Z", "regions": ["US-CA", "US-NY", "GB", "AU", ...], "categories": { "behavior": 156, "appearance": 134, "habitat": 98, ... }, "sources": { "wikipedia": 423, "api_ninjas": 234, "curated": 190 } }

POST /api/facts/collect

Manually trigger facts collection (for testing/admin use).

GET /health

Health check endpoint.

🏗️ Architecture

Layered Data Sources

  1. eBird API - Regional bird observations
  2. API Ninjas - Fun facts and characteristics
  3. Wikipedia - Rich descriptions and images

Smart Caching Strategy

  • Regional bird lists cached for 1 hour
  • Individual bird facts cached indefinitely
  • Graceful fallback to stale cache on API failures

Background Facts Collection

  • Cron Job: Automatically collects facts every few hours
  • Structured Storage: Facts are categorized and tagged
  • Global Coverage: Collects from 15+ regions worldwide
  • Fast Retrieval: Pre-collected facts serve in <100ms

🤖 AI-Powered Quality Curation

  • DeepSeek LLM Integration: Advanced language model for fact assessment
  • Quality Scoring: Each fact rated 1-10 for fascination level
  • Superlative Detection: Identifies record-breaking, unique, or extraordinary aspects
  • Fact Enhancement: AI rewrites facts for maximum clarity and impact
  • Emotional Impact Assessment: Measures wonder and amazement potential
  • Intelligent Categorization: Advanced categorization beyond basic topics

Error Handling

  • Multiple fallback data sources
  • Graceful degradation when APIs are unavailable
  • Comprehensive error logging

🔧 Setup & Configuration

Environment Variables (Optional)

The API works without API keys but provides enhanced functionality with them:

  • EBIRD_API_KEY: eBird API key for higher rate limits
  • API_NINJAS_KEY: API Ninjas key for additional facts

eBird Region Codes

Common region codes for the eBird API:

  • US-CA - California, USA
  • US-NY - New York, USA
  • GB - United Kingdom
  • AU - Australia
  • CA-ON - Ontario, Canada

💡 Usage Examples

JavaScript/TypeScript

// Get random regional bird const response = await fetch('/api/birds/random?region=US-CA'); const bird = await response.json(); console.log(`${bird.name}: ${bird.fact}`); // Get bird by coordinates const nearbyBird = await fetch('/api/birds/random?lat=40.7128&lng=-74.0060'); const birdData = await nearbyBird.json();

Python

import requests # Get random bird fact response = requests.get('https://your-api-url/api/birds/random') bird = response.json() print(f"{bird['name']}: {bird['fact']}") # Get regional birds regional_response = requests.get('https://your-api-url/api/birds/region/US-CA') birds = regional_response.json()

cURL

# Random bird fact curl "https://your-api-url/api/birds/random" # Regional bird with coordinates curl "https://your-api-url/api/birds/random?lat=37.7749&lng=-122.4194" # Specific bird species curl "https://your-api-url/api/birds/species/Blue%20Jay"

🎯 Use Cases

  • Nature Apps: Add regional bird information to hiking/nature apps
  • Educational Tools: Teach users about local wildlife
  • Chatbots: Provide interesting bird facts in conversations
  • Digital Signage: Display local bird information in visitor centers
  • Gamification: Create bird-spotting games with real regional data

🔄 Response Fields

FieldTypeDescription
namestringCommon bird name
scientificNamestringScientific/Latin name
factstringInteresting fact about the bird
wikipedia.summarystringWikipedia summary
wikipedia.imagestringImage URL
wikipedia.urlstringWikipedia page URL
regionstringRegion or coordinates used
sourcestring"regional" or "fallback"
cachedbooleanWhether result was cached

🚦 Rate Limits & Performance

  • Without API Keys: Limited by public API quotas
  • With eBird API Key: 100 requests per hour
  • Caching: Reduces external API calls by ~80%
  • Response Time: Typically 200-800ms for cached results

🛠️ Technical Stack

  • Backend: Hono framework with TypeScript
  • Storage: Val Town Blob storage for caching
  • APIs: eBird, API Ninjas, Wikipedia
  • Frontend: Vanilla JavaScript with Tailwind CSS
  • Deployment: Val Town serverless platform

📈 Monitoring & Debugging

The API includes comprehensive logging and error tracking:

  • Request/response logging
  • API failure tracking
  • Cache hit/miss ratios
  • Performance metrics

🤝 Contributing

This microservice demonstrates best practices for:

  • Multi-source data aggregation
  • Graceful error handling
  • Smart caching strategies
  • API design patterns
  • Documentation standards

📄 License

Open source - feel free to adapt for your own projects!

HTTP
  • index.ts
    greasegum--47…d9.web.val.run
Cron
  • collectFacts.ts
Code
backendcronfrontendREADME.mdtest-facts.tstest-llm.tstest.ts
FeaturesVersion controlCode intelligenceCLI
Use cases
TeamsAI agentsSlackGTM
ExploreDocsShowcaseTemplatesNewestTrendingAPI examplesNPM packages
PricingNewsletterBlogAboutCareers
We’re hiring!
Brandhi@val.townStatus
X (Twitter)
Discord community
GitHub discussions
YouTube channel
Bluesky
Terms of usePrivacy policyAbuse contact
© 2025 Val Town, Inc.