### Fetch Item Example (Python) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Demonstrates how to fetch a single item from the Hacker News API using Python's requests library. Ensure the 'requests' library is installed. ```python import requests ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/{item_id}.json" def fetch_item(item_id): """Fetches a single item from the Hacker News API.""" response = requests.get(ITEM_URL.format(item_id=item_id)) response.raise_for_status() # Raise an exception for bad status codes return response.json() # Example usage: # item = fetch_item(12345) # print(item) ``` -------------------------------- ### Fetch Item Example (curl) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md A command-line example using curl to fetch a single item from the Hacker News API. Useful for quick testing or scripting. ```bash curl "https://hacker-news.firebaseio.com/v0/item/12345.json" ``` -------------------------------- ### Job Item Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Example of a 'job' type item. Job postings include a title, description, and an optional URL for the posting. ```json { "by": "justin", "id": 192327, "score": 6, "text": "Justin.tv is hiring...", "time": 1210981217, "title": "Justin.tv is looking for a Lead Flash Engineer!", "type": "job", "url": "" } ``` -------------------------------- ### User Response Example Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md Example JSON response for a user profile. The structure includes user ID, karma, creation time, and a list of submitted item IDs. ```JSON { "about": "This is a test", "created": 1173923446, "id": "jl", "karma": 2937, "submitted": [8265435, 8168423, 8090946] } ``` -------------------------------- ### Fetch Top Stories Example (curl) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Command-line retrieval of top story IDs using curl. This is a simple way to get a list of current popular story IDs. ```bash curl "https://hacker-news.firebaseio.com/v0/topstories.json" ``` -------------------------------- ### Item Response Example Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md Example JSON response for a story item. The structure includes details like author, score, time, title, and URL. ```JSON { "by": "dhouston", "descendants": 71, "id": 8863, "kids": [8952, 9224, 8917, 8884, 8887], "score": 111, "time": 1175714200, "title": "My YC app: Dropbox - Throw away your USB drive", "type": "story", "url": "http://www.getdropbox.com/u/2/screencast.html" } ``` -------------------------------- ### Updates Type Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Shows an example of the Updates type, listing modified item IDs and user profiles. Check this endpoint periodically to discover changes. ```json { "items": [8423305, 8420805, 8423379, 8422504], "profiles": ["thefox", "mdda", "plinkplonk", "GBond"] } ``` -------------------------------- ### Fetch User Example (Python) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Illustrates fetching user profile information from the Hacker News API using Python. The 'requests' library is needed. ```python import requests USER_URL = "https://hacker-news.firebaseio.com/v0/user/{username}.json" def fetch_user(username): """Fetches a user's profile from the Hacker News API.""" response = requests.get(USER_URL.format(username=username)) response.raise_for_status() return response.json() # Example usage: # user_profile = fetch_user("pg") # print(user_profile) ``` -------------------------------- ### Comment Item Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Example of a 'comment' type item. Comments are replies and require a parent ID and contain text content. ```json { "by": "norvig", "id": 2921983, "kids": [2922097, 2922429, 2924562], "parent": 2921506, "text": "Aw shucks, guys ... you make me blush with your compliments.", "time": 1314211127, "type": "comment" } ``` -------------------------------- ### Basic GET Request for an Item Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md Demonstrates a basic GET request to retrieve a specific item by its ID. Ensure the `.json` extension is appended to the endpoint. ```http GET https://hacker-news.firebaseio.com/v0/item/8863.json ``` -------------------------------- ### Poll Item Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Example of a 'poll' type item. Polls have associated parts (options) and can have comments. ```json { "by": "pg", "descendants": 54, "id": 126809, "kids": [126822, 126823, 126993], "parts": [126810, 126811, 126812], "score": 46, "text": "", "time": 1204403652, "title": "Poll: What would happen if News.YC had explicit support for polls?", "type": "poll" } ``` -------------------------------- ### Story Item Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Example of a 'story' type item. Stories typically include a URL, title, score, and descendant comment count. ```json { "by": "dhouston", "descendants": 71, "id": 8863, "kids": [8952, 9224, 8917], "score": 111, "time": 1175714200, "title": "My YC app: Dropbox - Throw away your USB drive", "type": "story", "url": "http://www.getdropbox.com/u/2/screencast.html" } ``` -------------------------------- ### Fetch Item Example (JavaScript) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Demonstrates fetching a single item from the Hacker News API using the JavaScript Fetch API. Suitable for browser or Node.js environments. ```javascript const ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/{item_id}.json"; async function fetchItem(itemId) { try { const response = await fetch(ITEM_URL.replace('{item_id}', itemId)); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error("Error fetching item:", error); return null; } } // Example usage: // fetchItem(12345).then(item => console.log(item)); ``` -------------------------------- ### Fetch User Example (JavaScript) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Illustrates fetching user profile data from the Hacker News API using JavaScript's Fetch API. Useful for displaying user details or karma. ```javascript const USER_URL = "https://hacker-news.firebaseio.com/v0/user/{username}.json"; async function fetchUser(username) { try { const response = await fetch(USER_URL.replace('{username}', username)); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error("Error fetching user:", error); return null; } } // Example usage: // fetchUser('pg').then(user => console.log(user)); ``` -------------------------------- ### Fetch User Example (curl) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Using curl to fetch a user's profile information from the Hacker News API. Useful for checking user details directly from the terminal. ```bash curl "https://hacker-news.firebaseio.com/v0/user/pg.json" ``` -------------------------------- ### Poll Option Item Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Example of a 'pollopt' type item. These represent individual options within a poll and require a parent poll ID. ```json { "by": "pg", "id": 160705, "poll": 160704, "score": 335, "text": "Yes, ban them; I'm tired of seeing Valleywag stories on News.YC.", "time": 1207886576, "type": "pollopt" } ``` -------------------------------- ### Fetch Top Stories Example (Python) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Shows how to retrieve a list of top story IDs from the Hacker News API using Python. Requires the 'requests' library. ```python import requests TOP_STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json" def fetch_top_stories(): """Fetches a list of top story IDs from the Hacker News API.""" response = requests.get(TOP_STORIES_URL) response.raise_for_status() return response.json() # Example usage: # top_story_ids = fetch_top_stories() # print(f"Fetched {len(top_story_ids)} top story IDs.") ``` -------------------------------- ### Firebase Client Query Example Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md This example demonstrates a Firebase client query for retrieving top stories. Note that these operators are not available via the REST API and require the Firebase SDK. ```javascript ref('/v0/topstories').orderByChild('value') .limitToFirst(30) .on('value', ...) ``` -------------------------------- ### User Type Example Source: https://github.com/hackernews/api/blob/master/_autodocs/types.md Illustrates a Hacker News user object with its fields. Usernames are case-sensitive and karma is never negative. ```json { "about": "This is a test", "created": 1173923446, "id": "jl", "karma": 2937, "submitted": [8265435, 8168423, 8090946, 8090326] } ``` -------------------------------- ### Get User Profile Source: https://github.com/hackernews/api/blob/master/_autodocs/README.md This snippet demonstrates how to fetch a user's profile information using their username. ```APIDOC ## Get User Profile ### Description Fetches the profile information for a specific user. ### Method GET ### Endpoint `https://hacker-news.firebaseio.com/v0/user/{id}.json` ### Parameters #### Path Parameters - **id** (string) - Required - The username of the user. ### Request Example ```javascript const response = await fetch( 'https://hacker-news.firebaseio.com/v0/user/jl.json' ); const user = await response.json(); console.log(`${user.id}: ${user.karma} karma`); ``` ### Response #### Success Response (200) - **id** (string) - The user's ID (username). - **karma** (integer) - The user's karma score. - **about** (string) - A short biography of the user. - **submitted** (array) - An array of item IDs submitted by the user. #### Response Example ```json { "id": "jl", "karma": 17302, "about": "Founder of Y Combinator.", "submitted": [ 8863, 8864, 8865 ] } ``` ``` -------------------------------- ### Fetch Item Example (Python Admin SDK) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Fetches a single item from the Hacker News API using the Python Firebase Admin SDK. Requires the 'firebase-admin' library and service account credentials. ```python import firebase_admin from firebase_admin import db # Initialize Firebase Admin SDK (only once) # cred = firebase_admin.credentials.Certificate('path/to/your/serviceAccountKey.json') # firebase_admin.initialize_app(cred, { # 'databaseURL': 'https://your-project-id.firebaseio.com/' # }) def fetch_item_admin(item_id): """Fetches a single item using Firebase Admin SDK.""" ref = db.reference(f'v0/item/{item_id}') item_data = ref.get() return item_data # Example usage: # item = fetch_item_admin(12345) # print(item) ``` -------------------------------- ### Get User Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md Retrieves a specific user's profile information by their username. Supports pretty-printing the JSON output. ```APIDOC ## GET /v0/user/{username}.json ### Description Retrieves a specific user's profile information by their username. Supports pretty-printing the JSON output. ### Method GET ### Endpoint /v0/user/{username}.json ### Parameters #### Path Parameters - **username** (string) - Yes - Case-sensitive username #### Query Parameters - **print** (string) - — - Set to `pretty` for formatted JSON output ### Response #### Success Response (200) Returns a User object. See [types.md](types.md) for complete User schema. #### Response Example ```json { "about": "This is a test", "created": 1173923446, "id": "jl", "karma": 2937, "submitted": [8265435, 8168423, 8090946] } ``` ``` -------------------------------- ### Fetch Top Stories Example (JavaScript) Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md Shows how to retrieve a list of top story IDs using the JavaScript Fetch API. This is useful for building feeds or lists of current popular stories. ```javascript const TOP_STORIES_URL = "https://hacker-news.firebaseio.com/v0/topstories.json"; async function fetchTopStories() { try { const response = await fetch(TOP_STORIES_URL); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error("Error fetching top stories:", error); return []; } } // Example usage: // fetchTopStories().then(ids => console.log(`Fetched ${ids.length} top story IDs.`)); ``` -------------------------------- ### Comment Item Example Source: https://github.com/hackernews/api/blob/master/README.md Retrieves details for a comment item. Includes fields like 'by', 'id', 'kids', 'parent', 'text', 'time', and 'type'. ```javascript { "by" : "norvig", "id" : 2921983, "kids" : [ 2922097, 2922429, 2924562, 2922709, 2922573, 2922140, 2922141 ], "parent" : 2921506, "text" : "Aw shucks, guys ... you make me blush with your compliments.
Tell you what, Ill make a deal: I'll keep writing if you keep reading. K?",
"time" : 1314211127,
"type" : "comment"
}
```
--------------------------------
### Make Cross-Origin Requests from Browser
Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md
This example demonstrates making a direct fetch request to the Hacker News API from a web browser. The API supports CORS, so no special headers are needed.
```javascript
// Works directly from browser
fetch('https://hacker-news.firebaseio.com/v0/topstories.json')
.then(r => r.json())
.then(console.log);
```
--------------------------------
### Get Item Endpoint
Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md
Retrieve a specific item by its ID. Use the `print=pretty` query parameter for formatted JSON output. Returns a 404 if the item does not exist.
```HTTP
GET /v0/item/{id}.json
```
```HTTP
https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty
```
--------------------------------
### Job Item Example
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieves details for a job item. The specific fields for a job item are not detailed in the provided text, but it would typically include 'by', 'id', 'score', 'time', 'type', and 'text' for the job description.
```javascript
{
"by" : "joshb",
"id" : 192327,
"score" : 1,
"text" : "We're looking for a Haskell hacker to join us at Palm. We're building a new product and need someone who knows Haskell really well. You'll be working on the core systems. Email me at joshb@palm.com.",
"time" : 1204277141,
"type" : "job"
}
```
--------------------------------
### Pretty-print JSON Responses
Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md
Format JSON API responses for better readability. Examples include using 'jq', Python's 'json.tool', or the API's built-in '?print=pretty' query parameter.
```bash
# Using jq
curl https://hacker-news.firebaseio.com/v0/item/8863.json | jq .
```
```bash
# Using Python
curl https://hacker-news.firebaseio.com/v0/item/8863.json | python -m json.tool
```
```bash
# Using built-in query parameter
curl https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty
```
--------------------------------
### Story Item Example
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieves details for a story item. Includes fields like 'by', 'descendants', 'id', 'kids', 'score', 'time', 'title', 'type', and 'url'.
```javascript
{
"by" : "dhouston",
"descendants" : 71,
"id" : 8863,
"kids" : [ 8952, 9224, 8917, 8884, 8887, 8943, 8869, 8958, 9005, 9671, 8940, 9067, 8908, 9055, 8865, 8881, 8872, 8873, 8955, 10403, 8903, 8928, 9125, 8998, 8901, 8902, 8907, 8894, 8878, 8870, 8980, 8934, 8876 ],
"score" : 111,
"time" : 1175714200,
"title" : "My YC app: Dropbox - Throw away your USB drive",
"type" : "story",
"url" : "http://www.getdropbox.com/u/2/screencast.html"
}
```
--------------------------------
### Get User Endpoint
Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md
Retrieve a user's profile by their username. The username is case-sensitive. Use `print=pretty` for formatted JSON. Returns a 404 if the user does not exist or has no public activity.
```HTTP
GET /v0/user/{username}.json
```
```HTTP
https://hacker-news.firebaseio.com/v0/user/jl.json?print=pretty
```
--------------------------------
### Initialize Firebase Admin SDK
Source: https://github.com/hackernews/api/blob/master/_autodocs/firebase-integration.md
Initializes the Firebase Admin SDK with service account credentials and a database URL. Ensure 'path/to/serviceAccountKey.json' is correct.
```python
import firebase_admin
from firebase_admin import db
# Initialize
cred = firebase_admin.credentials.Certificate('path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://hacker-news.firebaseio.com'
})
ref = db.reference()
```
--------------------------------
### Load Top 10 Stories with Details
Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md
Fetches the IDs of the top 10 stories and then retrieves the full details for each story.
```bash
# Get top story IDs
curl https://hacker-news.firebaseio.com/v0/topstories.json | \
jq '.[0:10] | .[]' | \
while read id;
curl "https://hacker-news.firebaseio.com/v0/item/$id.json"
done
```
--------------------------------
### Get User Profile
Source: https://github.com/hackernews/api/blob/master/_autodocs/README.md
Retrieve a user's profile information, including their ID and karma, by making a GET request to the user endpoint with the user's ID.
```javascript
const response = await fetch(
'https://hacker-news.firebaseio.com/v0/user/jl.json'
);
const user = await response.json();
console.log(`${user.id}: ${user.karma} karma`);
```
--------------------------------
### Get Top Stories IDs
Source: https://github.com/hackernews/api/blob/master/README.md
Fetch an array of up to 500 top story IDs. This endpoint also includes job postings. Use this to get the latest popular content.
```json
[ 9129911, 9129199, 9127761, 9128141, 9128264, 9127792, 9129248, 9127092, 9128367, ..., 9038733 ]
```
--------------------------------
### Fetch Item Details in JavaScript
Source: https://github.com/hackernews/api/blob/master/_autodocs/SUMMARY.txt
Demonstrates fetching item details using the Fetch API and async/await in JavaScript. Requires item ID.
```javascript
async function fetchItem(itemId) {
const response = await fetch(`https://hacker-news.firebaseio.com/v0/item/${itemId}.json`);
const item = await response.json();
return item;
}
// Example usage:
// fetchItem(8863).then(item => console.log(item));
```
--------------------------------
### Max Item and Updates
Source: https://github.com/hackernews/api/blob/master/_autodocs/INDEX.md
Endpoints to get the maximum item ID and information about recent updates.
```APIDOC
## GET /v0/maxitem.json
### Description
Retrieves the ID of the most recent item on Hacker News.
### Method
GET
### Endpoint
/v0/maxitem.json
## GET /v0/updates.json
### Description
Retrieves information about the latest updates to items and profiles.
### Method
GET
### Endpoint
/v0/updates.json
```
--------------------------------
### Initialize Firebase Database
Source: https://github.com/hackernews/api/blob/master/_autodocs/firebase-integration.md
Initialize the Firebase Realtime Database with a specific URL. Ensure Firebase is configured in your project.
```swift
import FirebaseDatabase
let database = Database.database(url: "https://hacker-news.firebaseio.com")
```
--------------------------------
### Fetch Top Stories IDs in Android (Kotlin)
Source: https://github.com/hackernews/api/blob/master/_autodocs/SUMMARY.txt
Demonstrates fetching top story IDs using Kotlin and the Ktor client. Includes basic error handling.
```kotlin
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.runBlocking
val client = HttpClient()
fun getTopStoriesIds(): List>()
} else {
println("Error fetching top stories: ${response.status}")
emptyList()
}
} catch (e: Exception) {
println("Exception fetching top stories: ${e.message}")
emptyList()
}
}
}
// Example usage:
// val topIds = getTopStoriesIds()
// println(topIds.take(10))
```
--------------------------------
### Initialize Firebase Database
Source: https://github.com/hackernews/api/blob/master/_autodocs/firebase-integration.md
Initializes the Firebase app and database instance using the provided configuration. Required for all Firebase operations.
```javascript
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, get, onValue } from 'firebase/database';
const config = {
databaseURL: 'https://hacker-news.firebaseio.com'
};
const app = initializeApp(config);
const database = getDatabase(app);
```
--------------------------------
### Get Item
Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md
Retrieves a specific item from Hacker News by its unique identifier. Supports pretty-printing the JSON output.
```APIDOC
## GET /v0/item/{id}.json
### Description
Retrieves a specific item from Hacker News by its unique identifier. Supports pretty-printing the JSON output.
### Method
GET
### Endpoint
/v0/item/{id}.json
### Parameters
#### Path Parameters
- **id** (integer) - Yes - Unique item identifier
#### Query Parameters
- **print** (string) - — - Set to `pretty` for formatted JSON output
### Response
#### Success Response (200)
Returns an Item object. See [types.md](types.md) for complete Item schema.
#### Response Example
```json
{
"by": "dhouston",
"descendants": 71,
"id": 8863,
"kids": [8952, 9224, 8917, 8884, 8887],
"score": 111,
"time": 1175714200,
"title": "My YC app: Dropbox - Throw away your USB drive",
"type": "story",
"url": "http://www.getdropbox.com/u/2/screencast.html"
}
```
```
--------------------------------
### Set Request Timeouts
Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md
Configure timeouts for API requests to prevent indefinite hangs. Examples are provided for JavaScript, Python, and curl.
```javascript
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const response = await fetch(endpoint, {
signal: controller.signal
});
clearTimeout(timeout);
```
```python
response = requests.get(endpoint, timeout=10)
```
```bash
curl --max-time 10 https://hacker-news.firebaseio.com/v0/item/8863.json
```
--------------------------------
### Initialize Firebase Database
Source: https://github.com/hackernews/api/blob/master/_autodocs/firebase-integration.md
Initialize the Firebase Realtime Database instance with the specific Hacker News database URL. This is the first step before interacting with the database.
```kotlin
import com.google.firebase.database.FirebaseDatabase
val database = FirebaseDatabase.getInstance("https://hacker-news.firebaseio.com")
```
--------------------------------
### Missing Optional Fields in API Response
Source: https://github.com/hackernews/api/blob/master/_autodocs/data-handling.md
The API omits optional fields instead of setting them to null. This example shows the expected format.
```javascript
// What you receive for an item without an 'about' field:
{ "id": 8863, "type": "story", "by": "dhouston", ... }
// NOT this:
{ "id": 8863, "type": "story", "by": "dhouston", "about": null, ... }
```
--------------------------------
### Get User Data
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieve a user's profile information. Users are identified by case-sensitive IDs. Only users with public activity are available.
```json
{
"about" : "This is a test",
"created" : 1173923446,
"id" : "jl",
"karma" : 2937,
"submitted" : [ 8265435, 8168423, 8090946, 8090326, 7699907, 7637962, 7596179, 7596163, 7594569, 7562135, 7562111, 7494708, 7494171, 7488093, 7444860, 7327817, 7280290, 7278694, 7097557, 7097546, 7097254, 7052857, 7039484, 6987273, 6649999, 6649706, 6629560, 6609127, 6327951, 6225810, 6111999, 5580079, 5112008, 4907948, 4901821, 4700469, 4678919, 3779193, 3711380, 3701405, 3627981, 3473004, 3473000, 3457006, 3422158, 3136701, 2943046, 2794646, 2482737, 2425640, 2411925, 2408077, 2407992, 2407940, 2278689, 2220295, 2144918, 2144852, 1875323, 1875295, 1857397, 1839737, 1809010, 1788048, 1780681, 1721745, 1676227, 1654023, 1651449, 1641019, 1631985, 1618759, 1522978, 1499641, 1441290, 1440993, 1436440, 1430510, 1430208, 1385525, 1384917, 1370453, 1346118, 1309968, 1305415, 1305037, 1276771, 1270981, 1233287, 1211456, 1210688, 1210682, 1194189, 1193914, 1191653, 1190766, 1190319, 1189925, 1188455, 1188177, 1185884, 1165649, 1164314, 1160048, 1159156, 1158865, 1150900, 1115326, 933897, 924482, 923918, 922804, 922280, 922168, 920332, 919803, 917871, 912867, 910426, 902506, 891171, 807902, 806254, 796618, 786286, 764412, 764325, 642566, 642564, 587821, 575744, 547504, 532055, 521067, 492164, 491979, 383935, 383933, 383930, 383927, 375462, 263479, 258389, 250751, 245140, 243472, 237445, 229393, 226797, 225536, 225483, 225426, 221084, 213940, 213342, 211238, 210099, 210007, 209913, 209908, 209904, 209903, 170904, 165850, 161566, 158388, 158305, 158294, 156235, 151097, 148566, 146948, 136968, 134656, 133455, 129765, 126740, 122101, 122100, 120867, 120492, 115999, 114492, 114304, 111730, 110980, 110451, 108420, 107165, 105150, 104735, 103188, 103187, 99902, 99282, 99122, 98972, 98417, 98416, 98231, 96007, 96005, 95623, 95487, 95475, 95471, 95467, 95326, 95322, 94952, 94681, 94679, 94678, 94420, 94419, 94393, 94149, 94008, 93490, 93489, 92944, 92247, 91713, 90162, 90091, 89844, 89678, 89498, 86953, 86109, 85244, 85195, 85194, 85193, 85192, 84955, 84629, 83902, 82918, 76393, 68677, 61565, 60542, 47745, 47744, 41098, 39153, 38678, 37741, 33469, 12897, 6746, 5252, 4752, 4586, 4289 ]
}
```
--------------------------------
### Fetch and pretty-print a Hacker News item
Source: https://github.com/hackernews/api/blob/master/_autodocs/INDEX.md
This command fetches a specific item and formats the JSON response for better readability.
```bash
# Pretty print
curl https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty
```
--------------------------------
### Get Maximum Item ID
Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md
Fetches the ID of the most recently created item. This is useful for iterating backward through all items in the Hacker News database.
```json
9130260
```
--------------------------------
### Batch Loading with Firebase Admin SDK (Python)
Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md
Demonstrates batch loading multiple items using the Firebase Admin SDK in Python. This is more efficient than fetching items individually.
```python
import firebase_admin
from firebase_admin import db
# Assume Firebase Admin SDK is initialized
def fetch_multiple_items_admin(item_ids):
"""Fetches multiple items in a batch using Firebase Admin SDK."""
items_ref = db.reference('v0/item')
batch_data = {}
for item_id in item_ids:
item_ref = items_ref.child(str(item_id))
batch_data[item_id] = item_ref.get()
return batch_data
# Example usage:
# item_ids_to_fetch = [12345, 67890, 11223]
# items = fetch_multiple_items_admin(item_ids_to_fetch)
# print(items)
```
--------------------------------
### Load Top Stories
Source: https://github.com/hackernews/api/blob/master/_autodocs/README.md
This snippet demonstrates how to fetch a list of top story IDs and then retrieve the details for the first 10 stories. It utilizes Promise.all for concurrent fetching.
```javascript
// Get list of top story IDs
const response = await fetch(
'https://hacker-news.firebaseio.com/v0/topstories.json'
);
const storyIds = await response.json(); // [9129911, 9129199, ...]
// Fetch details for each
const stories = await Promise.all(
storyIds.slice(0, 10).map(id =>
fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
.then(r => r.json())
)
);
```
--------------------------------
### Get Updates for Items and Profiles
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieve changes for items and profiles. This endpoint provides a list of recently updated item IDs and profile names.
```json
{
"items" : [ 8423305, 8420805, 8423379, 8422504, 8423178, 8423336, 8422717, 8417484, 8423378, 8423238, 8423353, 8422395, 8423072, 8423044, 8423344, 8423374, 8423015, 8422428, 8423377, 8420444, 8423300, 8422633, 8422599, 8422408, 8422928, 8394339, 8421900, 8420902, 8422087 ],
"profiles" : [ "thefox", "mdda", "plinkplonk", "GBond", "rqebmm", "neom", "arram", "mcmancini", "metachris", "DubiousPusher", "dochtman", "kstrauser", "biren34", "foobarqux", "mkehrt", "nathanm412", "wmblaettler", "JoeAnzalone", "rcconf", "johndbritton", "msie", "cktsai", "27182818284", "kevinskii", "wildwood", "mcherm", "naiyt", "matthewmcg", "joelhaus", "tshtf", "MrZongle2", "Bogdanp" ]
}
```
--------------------------------
### Handling Non-existent Items from API
Source: https://github.com/hackernews/api/blob/master/_autodocs/data-handling.md
Shows how to check if an item fetched from the API is null, indicating that the item does not exist.
```javascript
// Item doesn't exist
const response = await fetch(
'https://hacker-news.firebaseio.com/v0/item/99999999.json'
);
const item = await response.json();
if (item === null) {
console.log('Item not found');
}
```
--------------------------------
### Get Ask Stories IDs
Source: https://github.com/hackernews/api/blob/master/README.md
Fetch an array of up to 200 latest Ask HN story IDs. Use this to retrieve questions posed to the community.
```json
[ 9127232, 9128437, 9130049, 9130144, 9130064, 9130028, 9129409, 9127243, 9128571, ..., 9120990 ]
```
--------------------------------
### Fetch Top Stories IDs in iOS (Swift)
Source: https://github.com/hackernews/api/blob/master/_autodocs/SUMMARY.txt
Demonstrates fetching top story IDs using Swift's URLSession. Includes basic error handling.
```swift
import Foundation
func getTopStoriesIds(completion: @escaping ([Int]) -> Void) {
guard let url = URL(string: "https://hacker-news.firebaseio.com/v0/topstories.json") else {
completion([])
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print("Error fetching top stories: \(error?.localizedDescription ?? "Unknown error")")
completion([])
return
}
do {
let decoder = JSONDecoder()
let storyIds = try decoder.decode([Int].self, from: data)
completion(storyIds)
} catch {
print("Error decoding top stories: \(error)")
completion([])
}
}
task.resume()
}
// Example usage:
// getTopStoriesIds { storyIds in
// print(storyIds.prefix(10))
// }
```
--------------------------------
### Get Updates Feed
Source: https://github.com/hackernews/api/blob/master/_autodocs/endpoints.md
Retrieves recently modified items and user profiles. Use this endpoint to stay synchronized with live changes on Hacker News.
```json
{
"items": [8423305, 8420805, 8423379],
"profiles": ["thefox", "mdda", "plinkplonk"]
}
```
--------------------------------
### Fetch data with JavaScript fetch
Source: https://github.com/hackernews/api/blob/master/_autodocs/rest-api-guide.md
Utilize the JavaScript fetch API to retrieve data from the Hacker News API. Includes an example with basic error handling.
```javascript
// Fetch item
const response = await fetch(
'https://hacker-news.firebaseio.com/v0/item/8863.json'
);
const story = await response.json();
console.log(story.title);
```
```javascript
// Fetch with error handling
async function fetchItem(id) {
try {
const response = await fetch(
`https://hacker-news.firebaseio.com/v0/item/${id}.json`
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error('Failed to fetch:', error);
return null;
}
}
```
--------------------------------
### Initialize Firebase App (JavaScript)
Source: https://github.com/hackernews/api/blob/master/_autodocs/MANIFEST.md
Initializes the Firebase SDK for use in a JavaScript/TypeScript application. Requires Firebase configuration object.
```javascript
import { initializeApp } from "firebase/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Now you can use other Firebase services, e.g.:
// import { getDatabase } from "firebase/database";
// const database = getDatabase(app);
```
--------------------------------
### Get User Information
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieves detailed information about a specific Hacker News user. The user's ID is case-sensitive. Only users with public activity are available.
```APIDOC
## GET /v0/user/{id}.json
### Description
Fetches a user's profile information, including their ID, creation date, karma, optional 'about' description, and a list of their submitted items.
### Method
GET
### Endpoint
`/v0/user/{id}.json`
### Parameters
#### Path Parameters
- **id** (string) - Required - The case-sensitive username of the user.
#### Query Parameters
None
### Request Example
`https://hacker-news.firebaseio.com/v0/user/jl.json?print=pretty`
### Response
#### Success Response (200)
- **id** (string) - The user's unique username.
- **created** (integer) - Creation date of the user, in Unix Time.
- **karma** (integer) - The user's karma.
- **about** (string) - The user's optional self-description. May contain HTML.
- **submitted** (array of integers) - List of the user's stories, polls and comments (item IDs).
```
--------------------------------
### Get Item by ID
Source: https://github.com/hackernews/api/blob/master/README.md
Retrieves a specific item (story, comment, job, poll, or pollopt) from the Hacker News API using its unique integer ID.
```APIDOC
## GET /v0/item/