Spaces:
Sleeping
Sleeping
File size: 13,578 Bytes
4093408 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 |
# Scheme Display API - Documentation
## Overview
This document describes the new API endpoints for displaying government schemes on the frontend with filtering, pagination, and search capabilities.
---
## π― New API Endpoints
### 1. **GET /schemes/all** - Get All Schemes with Filtering
Retrieves a paginated list of schemes with optional filtering.
#### Request Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `page` | integer | No | 1 | Page number (starts from 1) |
| `page_size` | integer | No | 10 | Number of schemes per page (max: 100) |
| `state` | string | No | null | Filter by state name |
| `category` | string | No | null | Filter by scheme category |
| `level` | string | No | null | Filter by level (Central/State) |
| `search` | string | No | null | Search text (searches in name, details, benefits, tags) |
#### Response Format
```json
{
"total": 3402,
"page": 1,
"page_size": 10,
"total_pages": 341,
"schemes": [
{
"scheme_name": "Scheme Name",
"slug": "scheme-slug",
"details": "Detailed description...",
"benefits": "Benefits offered...",
"eligibility": "Eligibility criteria...",
"application": "How to apply...",
"documents": "Required documents...",
"level": "State/Central",
"scheme_category": "Category name",
"tags": "tag1, tag2"
}
]
}
```
#### Example Requests
```bash
# Get first page of all schemes
GET http://127.0.0.1:8000/schemes/all
# Get schemes for specific state
GET http://127.0.0.1:8000/schemes/all?state=Karnataka&page=1&page_size=20
# Filter by category
GET http://127.0.0.1:8000/schemes/all?category=Agriculture
# Filter by level
GET http://127.0.0.1:8000/schemes/all?level=Central
# Search with text
GET http://127.0.0.1:8000/schemes/all?search=farmer
# Combined filters
GET http://127.0.0.1:8000/schemes/all?state=Maharashtra&category=Education&page=1&page_size=15
```
---
### 2. **GET /schemes/{slug}** - Get Scheme Details by Slug
Retrieves detailed information about a specific scheme.
#### Request Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `slug` | string | Yes | - | Unique scheme identifier |
| `language` | string | No | "en" | Language code for translation |
#### Response Format
```json
{
"scheme_name": "Scheme Name",
"slug": "scheme-slug",
"details": "Full details...",
"benefits": "Complete benefits...",
"eligibility": "Full eligibility criteria...",
"application": "Complete application process...",
"documents": "All required documents...",
"level": "State/Central",
"scheme_category": "Category",
"tags": "tags"
}
```
#### Example Requests
```bash
# Get scheme in English
GET http://127.0.0.1:8000/schemes/astpss
# Get scheme in Hindi
GET http://127.0.0.1:8000/schemes/astpss?language=hi
# Get scheme in Telugu
GET http://127.0.0.1:8000/schemes/pmsfbcs?language=te
```
---
### 3. **GET /schemes/categories** - Get All Categories
Retrieves all unique scheme categories.
#### Response Format
```json
{
"categories": [
"Agriculture,Rural & Environment",
"Business & Entrepreneurship",
"Education & Learning",
"Health & Wellness",
"Social welfare & Empowerment",
"Women and Child"
]
}
```
#### Example Request
```bash
GET http://127.0.0.1:8000/schemes/categories
```
---
### 4. **GET /schemes/stats** - Get Scheme Statistics
Retrieves statistics about all schemes.
#### Response Format
```json
{
"total_schemes": 3402,
"by_level": {
"State": 2850,
"Central": 552
},
"by_category": {
"Social welfare & Empowerment": 856,
"Business & Entrepreneurship": 642,
"Education & Learning": 432,
"Agriculture,Rural & Environment": 389,
"Health & Wellness": 267
},
"total_categories": 24
}
```
#### Example Request
```bash
GET http://127.0.0.1:8000/schemes/stats
```
---
## π¨ Frontend Implementation Examples
### React/Next.js Example
```javascript
// Fetch schemes with filters
const fetchSchemes = async (filters) => {
const params = new URLSearchParams({
page: filters.page || 1,
page_size: filters.pageSize || 10,
...(filters.state && { state: filters.state }),
...(filters.category && { category: filters.category }),
...(filters.level && { level: filters.level }),
...(filters.search && { search: filters.search })
});
const response = await fetch(
`http://127.0.0.1:8000/schemes/all?${params}`
);
return await response.json();
};
// Fetch single scheme
const fetchScheme = async (slug, language = 'en') => {
const response = await fetch(
`http://127.0.0.1:8000/schemes/${slug}?language=${language}`
);
return await response.json();
};
// Usage in component
const SchemesList = () => {
const [schemes, setSchemes] = useState([]);
const [filters, setFilters] = useState({
page: 1,
pageSize: 10,
state: '',
category: '',
search: ''
});
useEffect(() => {
fetchSchemes(filters).then(data => {
setSchemes(data.schemes);
});
}, [filters]);
return (
<div>
{/* Filter UI */}
{/* Scheme cards */}
</div>
);
};
```
---
## π Search & Filter Recommendations
### **RECOMMENDATION: Implement Filters on BACKEND**
#### β
Why Backend Filtering is Better:
1. **Performance**
- Only sends required data over network
- Reduces bandwidth usage
- Faster page loads (10 schemes vs 3402 schemes)
2. **Scalability**
- Database can grow without affecting frontend performance
- Efficient pagination
- Optimized queries
3. **Consistency**
- Same filtering logic across all platforms (web, mobile, etc.)
- Centralized business logic
- Easier to maintain
4. **User Experience**
- Faster search results
- Real-time filtering without loading all data
- Better mobile experience
5. **SEO Benefits**
- Server-side rendering possible
- Better indexing of individual scheme pages
- Faster initial page load
#### β Why Avoid Frontend Filtering:
1. **Performance Issues**
- Loading 3402+ schemes slows down initial page load
- Memory consumption on client devices
- Poor mobile performance
2. **Network Overhead**
- Large JSON payload on every page load
- Wasted bandwidth for unused data
3. **Maintenance**
- Duplicate filtering logic on frontend and backend
- Harder to debug issues
---
## π Backend Filtering Implementation
### Current Implementation Features:
#### 1. **State Filtering**
```python
# Searches in details and eligibility fields
if state and state != "All States":
filtered_df = filtered_df[
filtered_df['details'].str.contains(state, case=False, na=False) |
filtered_df['eligibility'].str.contains(state, case=False, na=False)
]
```
#### 2. **Category Filtering**
```python
# Case-insensitive partial matching
if category:
filtered_df = filtered_df[
filtered_df['schemeCategory'].str.contains(category, case=False, na=False)
]
```
#### 3. **Level Filtering**
```python
# Exact match for Central/State
if level:
filtered_df = filtered_df[
filtered_df['level'].str.lower() == level.lower()
]
```
#### 4. **Text Search**
```python
# Searches across multiple fields
if search:
search_mask = (
filtered_df['scheme_name'].str.contains(search, case=False, na=False) |
filtered_df['details'].str.contains(search, case=False, na=False) |
filtered_df['benefits'].str.contains(search, case=False, na=False) |
filtered_df['tags'].str.contains(search, case=False, na=False)
)
```
#### 5. **Pagination**
```python
# Efficient slicing
start_idx = (page - 1) * page_size
end_idx = start_idx + page_size
paginated_df = filtered_df.iloc[start_idx:end_idx]
```
---
## π― Recommended Frontend Architecture
### Option 1: Server-Side Rendering (SSR) - **Best for SEO**
```javascript
// Next.js Example
export async function getServerSideProps(context) {
const { page, state, category } = context.query;
const response = await fetch(
`http://127.0.0.1:8000/schemes/all?page=${page || 1}&state=${state || ''}&category=${category || ''}`
);
const data = await response.json();
return {
props: { schemes: data }
};
}
```
### Option 2: Client-Side with Debouncing - **Good UX**
```javascript
// React Hook for debounced search
import { useState, useEffect } from 'react';
import { debounce } from 'lodash';
const useSchemeSearch = () => {
const [filters, setFilters] = useState({});
const [schemes, setSchemes] = useState([]);
const [loading, setLoading] = useState(false);
const debouncedSearch = debounce(async (filters) => {
setLoading(true);
const data = await fetchSchemes(filters);
setSchemes(data.schemes);
setLoading(false);
}, 500); // Wait 500ms after user stops typing
useEffect(() => {
debouncedSearch(filters);
}, [filters]);
return { schemes, loading, setFilters };
};
```
### Option 3: Hybrid Approach - **Balanced**
```javascript
// Initial load: Server-side
// Filters: Client-side API calls
// Search: Debounced backend calls
const SchemeList = ({ initialSchemes }) => {
const [schemes, setSchemes] = useState(initialSchemes);
const handleFilterChange = async (newFilters) => {
const data = await fetchSchemes(newFilters);
setSchemes(data.schemes);
};
return (
<div>
<Filters onChange={handleFilterChange} />
<SchemeCards schemes={schemes} />
</div>
);
};
```
---
## π Performance Optimization Tips
### 1. **Caching**
```javascript
// Frontend caching with React Query
import { useQuery } from '@tanstack/react-query';
const useSchemes = (filters) => {
return useQuery({
queryKey: ['schemes', filters],
queryFn: () => fetchSchemes(filters),
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
});
};
```
### 2. **Lazy Loading**
```javascript
// Load more schemes on scroll
const SchemeList = () => {
const [page, setPage] = useState(1);
const handleScroll = () => {
if (/* bottom of page */) {
setPage(prev => prev + 1);
}
};
// Fetch next page and append
};
```
### 3. **Virtual Scrolling**
```javascript
// Use react-window for large lists
import { FixedSizeList } from 'react-window';
<FixedSizeList
height={600}
itemCount={schemes.length}
itemSize={120}
>
{SchemeCard}
</FixedSizeList>
```
---
## π± Mobile Optimization
### Recommended Approach for Mobile:
1. **Smaller Page Size**: Use `page_size=5` or `page_size=10` on mobile
2. **Lazy Loading**: Load more on scroll instead of pagination buttons
3. **Simplified Filters**: Show essential filters only
4. **Backend Filtering**: Critical for mobile performance
```javascript
// Detect device and adjust
const isMobile = window.innerWidth < 768;
const pageSize = isMobile ? 5 : 10;
fetchSchemes({ page: 1, page_size: pageSize });
```
---
## π Error Handling
### Backend Errors
```javascript
const fetchSchemes = async (filters) => {
try {
const response = await fetch(`/schemes/all?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to fetch schemes:', error);
// Show error toast/message to user
return { schemes: [], total: 0 };
}
};
```
---
## π Testing the API
### Using cURL
```bash
# Get all schemes
curl http://127.0.0.1:8000/schemes/all
# Filter by state
curl "http://127.0.0.1:8000/schemes/all?state=Karnataka"
# Search
curl "http://127.0.0.1:8000/schemes/all?search=farmer"
# Get specific scheme
curl http://127.0.0.1:8000/schemes/astpss
# Get statistics
curl http://127.0.0.1:8000/schemes/stats
```
### Using Python
```python
import requests
# Get schemes
response = requests.get(
'http://127.0.0.1:8000/schemes/all',
params={
'page': 1,
'page_size': 10,
'state': 'Karnataka',
'category': 'Agriculture'
}
)
data = response.json()
print(f"Found {data['total']} schemes")
```
---
## π Summary
### β
What We Built:
1. **4 new API endpoints** for scheme management
2. **Backend filtering** (state, category, level, search)
3. **Pagination** support
4. **Multi-language** scheme details
5. **Statistics** endpoint
### β
Recommendations:
1. **Use BACKEND filtering** - Better performance, scalability, UX
2. **Implement pagination** - Don't load all 3402 schemes at once
3. **Add debouncing** - For search input (500ms delay)
4. **Cache results** - Use React Query or SWR
5. **Lazy load** - For mobile and infinite scroll
### π― Best Practice:
**Backend handles filtering β Frontend displays results β User gets fast, smooth experience**
---
## π Support
For API documentation and interactive testing:
- Swagger UI: http://127.0.0.1:8000/docs
- ReDoc: http://127.0.0.1:8000/redoc
|