Skip to content

Commit f4f7ce7

Browse files
committed
feat(sprint-10): complete Story 10.3 - OpenAPI Spec Completion
Implemented comprehensive OpenAPI documentation with enhanced spec endpoints and client library generation. ## New Endpoints - GET /api/v1/docs/openapi.json - Enhanced OpenAPI spec with security schemes - GET /api/v1/docs/openapi.yaml - YAML format for better readability - GET /api/v1/docs/clients/{language} - Client libraries (Python, JavaScript, cURL) - GET /api/v1/docs/integrations/{framework} - Integration examples (Jupyter, Streamlit, Flask) - GET /api/v1/docs/postman - Postman collection for API testing ## Enhanced OpenAPI Spec Features - JWT Bearer authentication scheme (BearerAuth) - API Key authentication scheme (ApiKeyAuth with X-API-Key header) - Comprehensive API description with usage examples - Global security requirements - Error response schemas with examples - External documentation links - Server configurations - Categorized tags ## Testing - Created 34 comprehensive integration tests - 100% code coverage on APIDocumentationService - All tests passing (100% pass rate) - Tests cover endpoints, client generation, integrations, and documentation quality ## Dependencies - Added pyyaml for YAML export support ## Documentation - Updated SPRINT_10.md with Story 10.3 completion details - Sprint progress: 21/27 points (78%) - All acceptance criteria met Files modified: - apps/backend/app/main.py - apps/backend/pyproject.toml - apps/backend/uv.lock - SPRINT_10.md Files created: - apps/backend/tests/test_api/test_api_documentation_endpoints.py
1 parent 1665ee9 commit f4f7ce7

File tree

5 files changed

+664
-16
lines changed

5 files changed

+664
-16
lines changed

SPRINT_10.md

Lines changed: 65 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
**Sprint Duration**: Oct 9-11, 2025 (3 days - accelerated)
44
**Sprint Goal**: Implement comprehensive monitoring with Prometheus and Grafana, complete API documentation with OpenAPI specs, and fill integration test coverage gaps
55
**Velocity Target**: 27 story points
6-
**Points Completed**: 13/27 (48%)
6+
**Points Completed**: 21/27 (78%)
77
**Risk Level**: Low (non-breaking improvements)
8-
**Status**: 🚧 **IN PROGRESS** - Story 10.1 starting
8+
**Status**: 🚧 **IN PROGRESS** - Story 10.4 pending
99

1010
---
1111

@@ -20,7 +20,7 @@
2020
### Sprint Goals
2121
1. ✅ Prometheus metrics integration with system, ML, and business metrics
2222
2. ✅ Grafana dashboards for visualization
23-
3. Complete OpenAPI documentation for all endpoints
23+
3. Complete OpenAPI documentation for all endpoints
2424
4. ⏳ Integration test coverage >80%
2525
5. ⏳ Monitoring runbook for on-call engineers
2626

@@ -150,21 +150,62 @@
150150

151151
### Story 10.3: OpenAPI Spec Completion (Priority: 🟡, Points: 8)
152152

153-
**Status**: ⏳ **PENDING**
153+
**Status**: ✅ **COMPLETE**
154+
**Started**: 2025-10-09
155+
**Completed**: 2025-10-09
154156

155157
**As an** API consumer
156158
**I want** complete OpenAPI documentation
157159
**So that** I can integrate with the API easily
158160

159161
**Acceptance Criteria:**
160-
- [ ] All endpoints documented with request/response schemas
161-
- [ ] Authentication documented (JWT bearer token)
162-
- [ ] Error responses documented with examples
163-
- [ ] Interactive API docs at `/docs` endpoint
164-
- [ ] OpenAPI spec downloadable as JSON/YAML
162+
- [x] All endpoints documented with request/response schemas
163+
- [x] Authentication documented (JWT bearer token)
164+
- [x] Error responses documented with examples
165+
- [x] Interactive API docs at `/docs` endpoint
166+
- [x] OpenAPI spec downloadable as JSON/YAML
165167

166168
**Dependencies:**
167-
- Sprint 8: API versioning complete
169+
- Sprint 8: API versioning complete ✅
170+
171+
**Progress:**
172+
- ✅ Integrated existing APIDocumentationService into main.py
173+
- ✅ Created enhanced OpenAPI spec endpoints:
174+
- `/api/v1/docs/openapi.json` - Enhanced OpenAPI specification with security schemes
175+
- `/api/v1/docs/openapi.yaml` - YAML format for better readability
176+
- `/api/v1/docs/clients/{language}` - Client libraries (Python, JavaScript, cURL)
177+
- `/api/v1/docs/integrations/{framework}` - Integration examples (Jupyter, Streamlit, Flask)
178+
- `/api/v1/docs/postman` - Postman collection for API testing
179+
- ✅ Enhanced spec includes:
180+
- JWT Bearer authentication scheme (BearerAuth)
181+
- API Key authentication scheme (ApiKeyAuth - X-API-Key header)
182+
- Comprehensive API description with usage examples
183+
- Security requirements documented globally
184+
- Error response schemas with examples
185+
- External documentation links
186+
- Server configurations
187+
- Categorized tags for all endpoints
188+
- ✅ Added PyYAML dependency for YAML export support
189+
- ✅ Created comprehensive integration tests with 34 tests covering:
190+
- OpenAPI JSON and YAML endpoint testing
191+
- Client library generation (Python, JavaScript, cURL)
192+
- Integration examples (Jupyter, Colab, Streamlit, Flask)
193+
- Postman collection generation
194+
- Interactive documentation (/docs, /redoc)
195+
- Documentation coverage and completeness
196+
- Authentication documentation validation
197+
- Error response documentation
198+
- ✅ Achieved 100% code coverage on APIDocumentationService
199+
- ✅ All 34 tests passing (100% pass rate)
200+
201+
**Files Modified:**
202+
- `apps/backend/app/main.py` - Integrated documentation service and created 5 new endpoints
203+
- `apps/backend/pyproject.toml` - Added pyyaml dependency
204+
205+
**Files Created:**
206+
- `tests/test_api/test_api_documentation_endpoints.py` - 34 comprehensive integration tests
207+
208+
**Story 10.3 Status**: ✅ **COMPLETE**
168209

169210
---
170211

@@ -209,12 +250,12 @@
209250

210251
## Sprint Validation Gates
211252

212-
- [ ] Prometheus metrics exposed and accurate
213-
- [ ] 3 Grafana dashboards operational
214-
- [ ] OpenAPI spec complete at `/docs`
253+
- [x] Prometheus metrics exposed and accurate
254+
- [x] 3 Grafana dashboards operational
255+
- [x] OpenAPI spec complete at `/docs` and enhanced endpoints
215256
- [ ] Integration tests passing with >80% coverage
216257
- [ ] Monitoring runbook reviewed by team
217-
- [ ] All documentation updated
258+
- [x] All documentation updated
218259

219260
## Progress Tracking
220261

@@ -234,8 +275,16 @@
234275
- Configured alerts for critical thresholds
235276
- Wrote complete setup and usage documentation
236277
- All dashboards auto-refresh every 30s
237-
- **Progress**: 13/27 points (48%)
238-
- Next: Story 10.3 (OpenAPI Spec Completion) or Story 10.4 (Complete Integration Tests)
278+
- ✅ Completed Story 10.3: OpenAPI Spec Completion (8 points)
279+
- Integrated APIDocumentationService into main.py with 5 new documentation endpoints
280+
- Enhanced OpenAPI spec with JWT and API Key authentication schemes
281+
- Client library generation (Python, JavaScript, cURL)
282+
- Integration examples (Jupyter, Colab, Streamlit, Flask)
283+
- Postman collection generation for API testing
284+
- Comprehensive testing with 34 tests and 100% coverage
285+
- OpenAPI spec downloadable in JSON and YAML formats
286+
- **Progress**: 21/27 points (78%)
287+
- Next: Story 10.4 (Complete Integration Tests) or Story 10.5 (Monitoring Runbook)
239288

240289
---
241290

apps/backend/app/main.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
cache,
6262
transformations,
6363
)
64+
from app.services.api_documentation import APIDocumentationService
6465
from app.config import settings
6566
from app.db.mongodb import connect_to_mongo, close_mongo_connection
6667
from app.models.user_data import UserData
@@ -118,6 +119,11 @@ async def lifespan(app: FastAPI):
118119
lifespan=lifespan,
119120
)
120121

122+
# Initialize API documentation service
123+
# Note: Don't override app.openapi() as it causes recursion.
124+
# The enhanced spec is available at /api/v1/docs/openapi.json
125+
doc_service = APIDocumentationService(app)
126+
121127
# ✅ Apply CORS to the correct app instance
122128
app.add_middleware(
123129
CORSMiddleware,
@@ -241,3 +247,109 @@ async def metrics():
241247
Returns metrics in Prometheus text exposition format for scraping.
242248
"""
243249
return Response(content=get_metrics(), media_type=CONTENT_TYPE_LATEST)
250+
251+
252+
# API Documentation endpoints
253+
@app.get(f"{settings.API_V1_STR}/docs/openapi.json", tags=["documentation"])
254+
async def get_enhanced_openapi():
255+
"""
256+
Get enhanced OpenAPI specification with security schemes and examples.
257+
258+
Returns the complete API specification including:
259+
- All endpoints with request/response schemas
260+
- Authentication schemes (JWT Bearer, API Key)
261+
- Error response examples
262+
- Comprehensive descriptions and metadata
263+
"""
264+
return doc_service.generate_openapi_spec()
265+
266+
267+
@app.get(f"{settings.API_V1_STR}/docs/openapi.yaml", tags=["documentation"])
268+
async def get_enhanced_openapi_yaml():
269+
"""
270+
Get enhanced OpenAPI specification in YAML format.
271+
272+
Returns the same specification as the JSON endpoint but in YAML format
273+
for better readability and certain tooling compatibility.
274+
"""
275+
import yaml
276+
spec = doc_service.generate_openapi_spec()
277+
yaml_content = yaml.dump(spec, default_flow_style=False, sort_keys=False)
278+
return Response(content=yaml_content, media_type="application/x-yaml")
279+
280+
281+
@app.get(f"{settings.API_V1_STR}/docs/clients/{{language}}", tags=["documentation"])
282+
async def get_client_library(language: str):
283+
"""
284+
Get client library code for the specified language.
285+
286+
Supported languages:
287+
- python: Complete Python client with authentication and error handling
288+
- javascript: JavaScript/TypeScript client for Node.js and browsers
289+
- curl: cURL examples for all major endpoints
290+
291+
Args:
292+
language: Programming language for the client library
293+
294+
Returns:
295+
Source code for the client library
296+
297+
Raises:
298+
404: If the language is not supported
299+
"""
300+
from fastapi import HTTPException
301+
302+
libraries = doc_service.generate_client_libraries()
303+
if language not in libraries:
304+
raise HTTPException(
305+
status_code=404,
306+
detail=f"Language '{language}' not supported. Available: {', '.join(libraries.keys())}"
307+
)
308+
return Response(content=libraries[language], media_type="text/plain")
309+
310+
311+
@app.get(f"{settings.API_V1_STR}/docs/integrations/{{framework}}", tags=["documentation"])
312+
async def get_integration_example(framework: str):
313+
"""
314+
Get integration example for the specified framework.
315+
316+
Supported frameworks:
317+
- jupyter: Jupyter notebook integration example
318+
- colab: Google Colab integration example
319+
- streamlit: Streamlit app integration example
320+
- flask: Flask application integration example
321+
322+
Args:
323+
framework: Framework for the integration example
324+
325+
Returns:
326+
Source code for the integration example
327+
328+
Raises:
329+
404: If the framework is not supported
330+
"""
331+
from fastapi import HTTPException
332+
333+
examples = doc_service.generate_integration_examples()
334+
if framework not in examples:
335+
raise HTTPException(
336+
status_code=404,
337+
detail=f"Framework '{framework}' not supported. Available: {', '.join(examples.keys())}"
338+
)
339+
return Response(content=examples[framework], media_type="text/plain")
340+
341+
342+
@app.get(f"{settings.API_V1_STR}/docs/postman", tags=["documentation"])
343+
async def get_postman_collection():
344+
"""
345+
Get Postman collection for API testing.
346+
347+
Returns a complete Postman collection including:
348+
- All API endpoints with examples
349+
- Authentication configuration
350+
- Environment variables
351+
- Pre-request scripts for token management
352+
353+
The collection can be imported directly into Postman for interactive testing.
354+
"""
355+
return doc_service.generate_postman_collection()

apps/backend/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ dependencies = [
4040
"redis>=6.2.0",
4141
"gunicorn>=23.0.0",
4242
"prometheus-client>=0.19.0",
43+
"pyyaml>=6.0.3",
4344
]
4445

4546
[dependency-groups]

0 commit comments

Comments
 (0)