Back to Exercises
Fetch & API (Real Website Use)
20 Exercises Available
GET/POST, error handling, JSON — practical web development.
1.Medium
Fetch JSON (safe)
Create a function `fetchJson(url)` that returns JSON. Throw Error for non-2xx responses.
Sample Output:
await fetchJson("https://api.example.com/data") => {id: 1, name: "Test"}
await fetchJson("https://api.example.com/404") => throws Error("HTTP 404")View Solution
2.Medium
POST JSON (with headers)
Create a function `postJson(url, data)` that performs POST and returns response JSON.
Sample Output:
await postJson("https://api.example.com/users", {name: "John"}) => {id: 1, name: "John"}
await postJson("https://api.example.com/login", {email: "test@test.com"}) => {token: "..."}View Solution
3.Hard
Abort Fetch (cancel request)
Create a function `fetchWithAbort(url, ms)` that aborts request after ms milliseconds.
Sample Output:
await fetchWithAbort("https://api.example.com/data", 5000)
// If completes in < 5s: returns Response
// If takes > 5s: request aborted (throws error)View Solution
4.Easy
Build Query String
Function `toQuery(params)` banao jo object ko query string banaye.
Example: {q:"js", page:2} → "q=js&page=2"
Sample Output:
toQuery({q: "js", page: 2}) => "q=js&page=2"
toQuery({q: "js", page: null}) => "q=js"
toQuery({category: "electronics", price: 1000}) => "category=electronics&price=1000"View Solution
5.Easy
Normalize API Error Message
Create a function `getErrorMessage(err)` that returns string message.
- if err is Error → err.message
- if string → itself
- else → "Something went wrong"
Sample Output:
getErrorMessage(new Error("Network error")) => "Network error"
getErrorMessage("Invalid input") => "Invalid input"
getErrorMessage({code: 500}) => "Something went wrong"View Solution
6.Medium
Fetch with Retry Logic
Function `fetchWithRetry(url, options, maxRetries)` banao jo fetch ko retry kare on failure.
Example: fetchWithRetry("https://api.example.com/data", {}, 3)
Sample Output:
await fetchWithRetry("https://api.example.com/data", {}, 3)
// Retries up to 3 times on failureView Solution
7.Easy
Fetch with Request Headers
Function `fetchWithHeaders(url, headers)` banao jo custom headers ke saath fetch kare.
Example: fetchWithHeaders("https://api.example.com", {Authorization: "Bearer token"})
Sample Output:
await fetchWithHeaders("https://api.example.com", {Authorization: "Bearer token"})
// Fetches with custom headersView Solution
8.Medium
Parse Response Based on Content-Type
Function `parseResponse(response)` banao jo response content-type ke basis par parse kare.
Example: parseResponse(response) => JSON/text/blob based on content-type
Sample Output:
await parseResponse(response) // Returns parsed data based on content-type
View Solution
9.Hard
Fetch with Timeout and Fallback
Function `fetchWithTimeout(url, options, timeout, fallback)` banao jo timeout pe fallback return kare.
Example: fetchWithTimeout(url, {}, 5000, () => getCachedData())
Sample Output:
await fetchWithTimeout(url, {}, 5000, () => getCachedData())
// On timeout: returns cached dataView Solution
10.Easy
Batch Fetch Multiple URLs
Function `batchFetch(urls, options)` banao jo multiple URLs ko parallel me fetch kare.
Example: batchFetch(["url1", "url2"], {}) => [response1, response2]
Sample Output:
await batchFetch(["url1", "url2"], {}) => [response1, response2]
// Fetches all URLs in parallelView Solution
11.Medium
Fetch with Request Interceptor
Function `fetchWithInterceptor(url, options, interceptor)` banao jo request ko intercept kare before sending.
Example: fetchWithInterceptor(url, {}, (req) => {req.headers.set("X-Custom", "value")})
Sample Output:
await fetchWithInterceptor(url, {}, (req) => req.headers.set("X-Custom", "value"))
// Intercepts and modifies requestView Solution
12.Easy
Fetch JSON with Default Value
Function `fetchJsonSafe(url, defaultValue)` banao jo JSON fetch kare aur fail ho to default return kare.
Example: fetchJsonSafe("https://api.example.com", {})
Sample Output:
await fetchJsonSafe("https://api.example.com", {}) => (JSON or {})
// Returns default on failureView Solution
13.Easy
Check if URL is Accessible
Function `isUrlAccessible(url)` banao jo check kare ki URL accessible hai ya nahi.
Example: isUrlAccessible("https://example.com") => true/false
Sample Output:
await isUrlAccessible("https://example.com") => true (if accessible)
await isUrlAccessible("https://invalid") => falseView Solution
14.Hard
Fetch with Progress Tracking
Function `fetchWithProgress(url, onProgress)` banao jo fetch progress track kare.
Example: fetchWithProgress(url, (loaded, total) => console.log(loaded/total))
Sample Output:
await fetchWithProgress(url, (loaded, total) => console.log(loaded/total)) // Calls onProgress with loaded/total
View Solution
15.Medium
Fetch with Cache Control
Function `fetchWithCache(url, options, cacheTime)` banao jo response ko cache kare.
Example: fetchWithCache(url, {}, 60000) → caches for 60 seconds
Sample Output:
await fetchWithCache(url, {}, 60000)
// Caches response for 60 secondsView Solution
16.Hard
Fetch with Rate Limiting
Function `createRateLimitedFetch(limit, window)` banao jo fetch requests ko rate limit kare.
Example: const fetch = createRateLimitedFetch(10, 60000); → max 10 requests per minute
Sample Output:
const fetch = createRateLimitedFetch(10, 60000); await fetch(url); // Limits to 10 requests per minute
View Solution
17.Easy
Fetch with Authentication Token
Function `fetchWithAuth(url, token)` banao jo Authorization header ke saath fetch kare.
Example: fetchWithAuth("https://api.example.com", "Bearer token123")
Sample Output:
await fetchWithAuth("https://api.example.com", "token123")
// Fetches with Authorization headerView Solution
18.Medium
Fetch and Handle Different Status Codes
Function `fetchWithStatusHandling(url)` banao jo different status codes ko handle kare.
Example: fetchWithStatusHandling(url) → 200: data, 404: null, 500: error
Sample Output:
await fetchWithStatusHandling(url) // 200: returns JSON, 404: returns null, 500+: throws error
View Solution
19.Medium
Fetch with Request Body Validation
Create a function `fetchWithValidation(url, data, validator)` that validates request body before sending.
Example: fetchWithValidation(url, data, (d) => d.name)
Sample Output:
await fetchWithValidation(url, data, (d) => d.name) // Validates data before sending
View Solution
20.Easy
Fetch with Response Transformation
Create a function `fetchWithTransform(url, transform)` that transforms response.
Example: fetchWithTransform(url, (data) => data.items)
Sample Output:
await fetchWithTransform(url, (data) => data.items) // Transforms response data
View Solution