Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:54:44 +08:00
commit f14894054f
17 changed files with 15633 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
{
"name": "sap-api-style",
"description": "Comprehensive guidance for documenting SAP APIs following official SAP API Style Guide standards. Covers REST, OData, OpenAPI, Javadoc, JSDoc, and API Business Hub compliance.",
"version": "1.0.0",
"author": {
"name": "Zhongwei Li",
"email": "zhongweili@tubi.tv"
},
"skills": [
"./"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# sap-api-style
Comprehensive guidance for documenting SAP APIs following official SAP API Style Guide standards. Covers REST, OData, OpenAPI, Javadoc, JSDoc, and API Business Hub compliance.

423
SKILL.md Normal file
View File

@@ -0,0 +1,423 @@
---
name: sap-api-style
description: |
This skill provides comprehensive guidance for documenting SAP APIs following official SAP API Style Guide standards.
It should be used when creating or reviewing API documentation for REST, OData, Java, JavaScript, .NET, or C/C++ APIs.
The skill covers naming conventions, documentation comments, OpenAPI specifications, quality checklists, deprecation policies,
and manual documentation templates. It ensures consistency with SAP API Business Hub standards and industry best practices.
Keywords: SAP API, REST, OData, OpenAPI, Swagger, Javadoc, JSDoc, XML documentation, API Business Hub, API naming,
API deprecation, x-sap-stateInfo, Entity Data Model, EDM, documentation tags, API quality, API templates
license: GPL-3.0
metadata:
version: "1.1.0"
last_verified: "2025-11-27"
source_version: "2025.01"
source_commit: "902247f3afb6a0cb3fa110b284bb5d93a65c1268"
source_license: "CC-BY-4.0"
---
# SAP API Style Guide
## Related Skills
- **sap-cap-capire**: Use for OData service documentation, CAP API patterns, and service definition standards
- **sap-fiori-tools**: Use for API consumption patterns, Fiori app integration, and OData best practices
- **sap-abap**: Use when documenting ABAP APIs, implementing REST services, or following API design patterns
- **sapui5**: Use for frontend API integration, OData consumption, and UI service patterns
- **sap-btp-cloud-platform**: Use for BTP service API documentation and integration patterns
## Table of Contents
1. [Overview](#overview)
2. [When to Use This Skill](#when-to-use-this-skill)
3. [Quick Decision Tree](#quick-decision-tree)
4. [Core Principles](#core-principles)
5. [Quick Reference Tables](#quick-reference-tables)
6. [Templates Available](#templates-available)
7. [Reference Files](#reference-files)
8. [Instructions for Use](#instructions-for-use)
9. [Common Pitfalls to Avoid](#common-pitfalls-to-avoid)
10. [External Resources](#external-resources)
11. [Updates and Maintenance](#updates-and-maintenance)
## Overview
This skill provides comprehensive guidance for documenting SAP APIs according to official SAP API Style Guide standards. It covers all major API types and documentation approaches used across the SAP ecosystem.
**Documentation Source**: [https://github.com/SAP-docs/api-style-guide](https://github.com/SAP-docs/api-style-guide) (76 files extracted)
**Last Verified**: 2025-11-21
## When to Use This Skill
Use this skill when:
- **Creating API documentation** for REST, OData, Java, JavaScript, .NET, or C/C++ APIs
- **Writing OpenAPI specifications** for SAP API Business Hub
- **Reviewing API names** for SAP naming convention compliance
- **Documenting API parameters, responses, operations** with proper formatting
- **Creating manual API documentation** using SAP templates
- **Writing documentation comments** in source code (Javadoc, JSDoc, XML comments)
- **Implementing API deprecation** following SAP lifecycle policies
- **Developing developer guides** or service documentation
- **Performing quality checks** on API documentation
- **Publishing APIs** to SAP API Business Hub
## Quick Decision Tree
### What Type of API?
```
REST/OData API
├─ Auto-generated (OpenAPI/Swagger)?
│ └─ references/rest-odata-openapi-guide.md
│ • OpenAPI specification standards
│ • Package, API, operation descriptions
│ • Parameters, responses, components
│ • SAP API Business Hub requirements
└─ Manually written?
└─ references/manual-templates-guide.md
• REST templates (2-level: overview → method)
• OData templates (3-level: service → resource → operation)
• Complete field requirements
• templates/ directory for ready-to-use files
Native Library API
├─ Java → references/java-javascript-dotnet-guide.md
├─ JavaScript → references/java-javascript-dotnet-guide.md
├─ .NET (C#) → references/java-javascript-dotnet-guide.md
└─ C/C++ → references/java-javascript-dotnet-guide.md
• Documentation comments structure
• Language-specific tags
• Templates for classes, methods, enums
• Complete code examples
```
### What Task?
```
Naming
└─ references/naming-conventions.md
• REST/OData naming (resources, parameters, URIs)
• Native library naming (classes, methods, constants)
• Common mistakes to avoid
Writing Descriptions
└─ references/rest-odata-openapi-guide.md
• Package descriptions
• API details (info object)
• Operations, parameters, responses
Quality Assurance
└─ references/quality-processes.md
• Complete API Quality Checklist
• Review workflows
• Development team guidelines
Deprecating APIs
└─ references/deprecation-policy.md
• Lifecycle states (beta, active, deprecated, decommissioned)
• Timeline requirements (12+ months support)
• Required metadata (x-sap-stateInfo)
Developer Guides
└─ references/developer-guides.md
• Structure guidelines
• Content selection
• Code sample standards
```
## Core Principles
### 1. Consistency Across SAP APIs
All SAP API documentation follows consistent conventions:
- **Naming**: Language-specific (camelCase, PascalCase, kebab-case)
- **Structure**: Hierarchical with clear navigation
- **Formatting**: Sentences start with capitals, end with periods
- **Language**: American English
### 2. API-Type-Specific Standards
| API Type | Standard | Tool | Documentation |
|----------|----------|------|---------------|
| REST | OpenAPI 3.0.3 | Swagger | [Spec](https://spec.openapis.org/) |
| OData | v4.01, v3.0, v2.0 | Various | [OData.org](https://www.odata.org/) |
| Java | Javadoc | javadoc | [Oracle](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html) |
| JavaScript | JSDoc 3 | jsdoc | [JSDoc.app](https://jsdoc.app/) |
| .NET | XML Comments | DocFX | [Microsoft](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/) |
| C/C++ | Doxygen | doxygen | [Doxygen.nl](https://www.doxygen.nl/) |
### 3. Progressive Disclosure
Documentation organized hierarchically:
- **High-level overviews** provide context and navigation
- **Detailed references** cover specific APIs, methods, operations
- **Examples and templates** demonstrate practical usage
### 4. Quality Standards
All documentation must:
- ✅ Be reviewed by User Assistance (UA) developers
- ✅ Use consistent naming and terminology
- ✅ Include complete parameter and response descriptions
- ✅ Avoid sensitive data in examples
- ✅ Provide working code examples
- ✅ Maintain accurate links and cross-references
## Quick Reference Tables
### Character Limits
| Element | Limit | Use Case |
|---------|-------|----------|
| API Title | 80 | `info.title` in OpenAPI |
| API Short Text | 180 | `x-sap-shortText` |
| Package Short Desc | 250 | Package tile description |
| Operation Summary | 255 | Operation summary line |
| Description | 1024 | General descriptions |
### API Naming Rules
**General Rules** (all API types):
- ❌ Don't include "API" in name: ~~"Custom Forms API"~~ → ✅ "Custom Forms"
- ❌ Don't include "SAP" prefix: ~~"SAP Document Approval"~~ → ✅ "Document Approval"
- ❌ Don't use verbs: ~~"Configuring Portal"~~ → ✅ "Portal Configuration"
- ✅ Capitalize words properly
- ✅ Avoid technical specifics (REST, OData, etc.)
See `references/naming-conventions.md` for complete language-specific rules.
### Common Documentation Tags
**Java/JavaScript**:
- `@param <name> <description>` - Parameter documentation
- `@return <description>` - Return value
- `@throws <class> <description>` - Exception
- `@deprecated <description>` - Deprecation notice
**.NET**:
- `<summary>` - Brief description
- `<param name="">` - Parameter
- `<returns>` - Return value
- `<exception cref="">` - Exception
See `references/java-javascript-dotnet-guide.md` for complete tag reference.
### API Lifecycle States
| State | Definition | Support | Metadata Required |
|-------|-----------|---------|-------------------|
| **Beta** | Pre-production testing | No guarantees | `state: beta` |
| **Active** | Production-ready (default) | Full support | Optional |
| **Deprecated** | Replaced by successor | 12+ months | `state`, `deprecationDate`, `successorApi` |
| **Decommissioned** | Fully retired | None | Document removal |
See `references/deprecation-policy.md` for complete timeline and process requirements.
## Templates Available
Ready-to-use templates in `templates/` directory:
### REST API Templates (2-Level)
1. **rest-api-overview-template.md** - Resource-level overview
2. **rest-api-method-template.md** - Individual endpoint details
### OData API Templates (3-Level)
1. **odata-service-overview-template.md** - Complete service overview
2. **odata-resource-template.md** - Individual resource/entity set
3. **odata-operation-template.md** - Specific operation details
All templates include:
- Clear "How to Use" instructions
- [Placeholder text] for customization
- Complete section structure
- Working examples
- Inline guidance
## Reference Files
### Complete Guides Available
1. **rest-odata-openapi-guide.md** (2,800 lines)
- Complete OpenAPI specification guidelines
- Package, API, operation descriptions
- Parameters, responses, components
- Security schemes, tags, external docs
- Character limits and anti-patterns
2. **manual-templates-guide.md** (2,765 lines)
- REST API templates (2-level hierarchy)
- OData API templates (3-level hierarchy)
- Complete template structures
- Field-by-field requirements
- Best practices and examples
3. **naming-conventions.md** (2,059 lines)
- REST/OData naming rules (resources, parameters, URIs)
- Native library naming (classes, methods, constants, packages)
- Language-specific conventions
- Common mistakes with fixes
- Decision trees and reference tables
4. **quality-processes.md** (1,774 lines)
- Complete API Quality Checklist
- Review workflows (developer + UA collaboration)
- Development team guidelines
- Common review findings and solutions
- Process flowcharts
5. **java-javascript-dotnet-guide.md** (1,517 lines)
- Documentation comments structure
- Language-specific tags (Java, JavaScript, .NET, C/C++)
- Templates for classes, methods, enums
- Complete code examples
- Best practices by language
6. **developer-guides.md** (704 lines)
- Guide structure standards
- Topic types (concept, reference, task)
- Content selection criteria
- Code sample standards (compilable, concise, commented)
- Best practices
7. **deprecation-policy.md** (664 lines)
- API lifecycle states (beta, active, deprecated, decommissioned)
- Timeline requirements (12+ months support, 24+ months lifespan)
- Required metadata (x-sap-stateInfo, artifact.json)
- Decommission process
- Complete examples
8. **glossary-resources.md** (472 lines)
- Complete terminology definitions (API, OData, OpenAPI, etc.)
- External resource links (standards, tools, SAP resources)
- Quick reference tables
- Tool documentation links
- Content extraction and organization tracking
- Source file mapping from SAP documentation
- Consolidation and adaptation notes
## Bundled Resources
This skill includes comprehensive documentation and templates organized for optimal use:
### Reference Guides (`references/`)
- 9 detailed reference files (10,861 total lines)
- Complete coverage of SAP API Style Guide standards
- Progressive disclosure architecture for efficient loading
### Template Files (`templates/`)
1. **rest-api-overview-template.md** (217 lines) - Level 1 REST overview
2. **rest-api-method-template.md** (477 lines) - Level 2 REST method details
3. **odata-service-overview-template.md** (411 lines) - Level 1 OData service
4. **odata-resource-template.md** (557 lines) - Level 2 OData resource
5. **odata-operation-template.md** (681 lines) - Level 3 OData operation
Total: 2,343 lines of ready-to-use templates
## Instructions for Use
### Step 1: Identify API Type
Determine if you're documenting REST, OData, Java, JavaScript, .NET, or C/C++ API.
### Step 2: Choose Approach
**Auto-Generated**: Write documentation comments in source code → Use appropriate tags → Submit for review
**Manual**: Select template from `templates/` → Customize [placeholders] → Follow hierarchy → Validate with checklist
### Step 3: Apply Standards
Consult appropriate reference file:
- **Naming**: `naming-conventions.md`
- **Descriptions**: `rest-odata-openapi-guide.md` or `java-javascript-dotnet-guide.md`
- **Quality**: `quality-processes.md`
- **Deprecation**: `deprecation-policy.md`
### Step 4: Quality Check
Before publishing:
1. Review against API Quality Checklist (`quality-processes.md`)
2. Verify naming conventions (`naming-conventions.md`)
3. Check character limits (see Quick Reference Tables above)
4. Validate no sensitive data in examples
5. Test all code examples
6. Verify links work
7. Obtain UA developer review
### Step 5: Publish
- **REST/OData**: Submit to SAP API Business Hub
- **Java/JavaScript/.NET**: Generate with appropriate tool (Javadoc, JSDoc, DocFX)
- **Developer Guides**: Publish to SAP Help Portal or product documentation
## Common Pitfalls to Avoid
**Naming**:
- ❌ Including "API": ~~"Custom Forms APIs"~~ → ✅ "Custom Forms"
- ❌ Using "SAP" prefix: ~~"SAP Document Approval"~~ → ✅ "Document Approval"
- ❌ Using verbs: ~~"Configuring Portal"~~ → ✅ "Portal Configuration"
**Descriptions**:
- ❌ Second person: ~~"This operation creates..."~~ → ✅ "Creates a new user"
- ❌ Generic responses: ~~"No content"~~ → ✅ "Product is out of stock"
- ❌ Repeating summary in description
**Documentation**:
- ❌ Skipping UA review
- ❌ Including sensitive data in examples
- ❌ Missing required tags
- ❌ Inconsistent terminology
See individual reference files for complete anti-patterns and fixes.
## External Resources
### Standards
- **OpenAPI Specification**: [https://spec.openapis.org/oas/latest.html](https://spec.openapis.org/oas/latest.html)
- **OData v4.01**: [https://www.odata.org/documentation/](https://www.odata.org/documentation/)
- **Javadoc**: [https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)
- **JSDoc 3**: [https://jsdoc.app/](https://jsdoc.app/)
- **Doxygen**: [https://www.doxygen.nl/](https://www.doxygen.nl/)
### SAP Resources
- **SAP API Business Hub**: [https://api.sap.com/](https://api.sap.com/)
- **SAP Developer Center**: [https://developers.sap.com/](https://developers.sap.com/)
- **SAP Help Portal**: [https://help.sap.com/](https://help.sap.com/)
- **SAP Community**: [https://community.sap.com/](https://community.sap.com/)
### Source
- **SAP API Style Guide**: [https://github.com/SAP-docs/api-style-guide](https://github.com/SAP-docs/api-style-guide)
## Updates and Maintenance
**Source Version**: SAP API Style Guide 2025.01 (verified against commit 902247f)
**Recent Changes**:
- Source repository updated 2025-10-28
- Reference file line counts verified and updated
- Added comprehensive Table of Contents for navigation
- Added Bundled Resources section for content discovery
**To Update This Skill**:
1. Check source repository for changes: [https://github.com/SAP-docs/api-style-guide](https://github.com/SAP-docs/api-style-guide)
2. Review "What's New in the Style Guide"
3. Update affected reference files
4. Update templates if standards changed
5. Update "Last Verified" date
**Quarterly Review Recommended**: Check for updates every 3 months
**Next Review**: 2026-02-27
---
**Skill Version**: 1.1.0
**Last Updated**: 2025-11-27
**License**: GPL-3.0
**Maintainer**: SAP Skills Team | [https://github.com/secondsky/sap-skills](https://github.com/secondsky/sap-skills)

97
plugin.lock.json Normal file
View File

@@ -0,0 +1,97 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:secondsky/sap-skills:skills/sap-api-style",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "09539a98b0dc5ce0f7a028ed8e8cab96d1c3fe1c",
"treeHash": "6f7f6999b5610c56069d2170c4f46ed9e4ebc4ebdd807e487b188f7de24a5b7c",
"generatedAt": "2025-11-28T10:28:10.900382Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "sap-api-style",
"description": "Comprehensive guidance for documenting SAP APIs following official SAP API Style Guide standards. Covers REST, OData, OpenAPI, Javadoc, JSDoc, and API Business Hub compliance.",
"version": "1.0.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "bd8bef477b2a94275b53eec22d0933e1d58ca04047f0efebca7cc46d7d8d0130"
},
{
"path": "SKILL.md",
"sha256": "af2099a2f3dfcc3d089d0faae30f6d45e65c5432267a13c1dffb09bfccc4a5f6"
},
{
"path": "references/developer-guides.md",
"sha256": "b340234e627f4592b5f3d43c27b81ed853b222b8efd84ba927dedb0e6e95d12d"
},
{
"path": "references/deprecation-policy.md",
"sha256": "afb9ae0ddd799899e2fa020c43de3d249abf70d7dbb9dd7af4ce2eea31b9e0a4"
},
{
"path": "references/naming-conventions.md",
"sha256": "10e0719a15752ba251eeafc999a4061b767b30d106f76fad61314830be446c79"
},
{
"path": "references/glossary-resources.md",
"sha256": "a28da9075d577298cb2f6e1b7aba4537eb2d8684c6a344eb087156b38922a7ce"
},
{
"path": "references/java-javascript-dotnet-guide.md",
"sha256": "b542327631952576a17618975de1cb99b75b037422d674e7bb8dbd575e99a9cb"
},
{
"path": "references/rest-odata-openapi-guide.md",
"sha256": "8afd1e9a7578cc1a59ccdb4cebf18cd44c0f7f479afe86d559d7cc06a719d209"
},
{
"path": "references/manual-templates-guide.md",
"sha256": "8b9d56b99c47ae1fc723a64c46b0961041f4319a58f66c0668066e45b31be9b1"
},
{
"path": "references/quality-processes.md",
"sha256": "c7529c41d605ae9b9bb3ea361dc511860e452d08397af6d5f81ceaefb982839b"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "b0b221e769fd1b7d918fe89a7d690aca233ec782ac72becc6c6f47ee3a319655"
},
{
"path": "templates/rest-api-method-template.md",
"sha256": "10883dffee3ff7ebc73729d71468b3b4c5f67afaa03fd7c85b4bb84b5f8c6c48"
},
{
"path": "templates/odata-service-overview-template.md",
"sha256": "3da25ef899201d5db2bab983515a7ffffa939986da99dae1365316b090baa73d"
},
{
"path": "templates/rest-api-overview-template.md",
"sha256": "fd3f197ac57124105613351105978a41935d5f0746a410e287c035686cfa6f45"
},
{
"path": "templates/odata-operation-template.md",
"sha256": "8156816cebacdd820aedc8ac0f42b90ff87705e944064cffc8f1371b2a649a48"
},
{
"path": "templates/odata-resource-template.md",
"sha256": "c8f0b49a39e53847a20b53874a347b88dc172be3cfa440a4c3fb8b9d2f3d2ec4"
}
],
"dirSha256": "6f7f6999b5610c56069d2170c4f46ed9e4ebc4ebdd807e487b188f7de24a5b7c"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

View File

@@ -0,0 +1,664 @@
# SAP API Deprecation Policy
**Source**: [https://github.com/SAP-docs/api-style-guide/blob/main/docs/api-deprecation-policy-65a10e3.md](https://github.com/SAP-docs/api-style-guide/blob/main/docs/api-deprecation-policy-65a10e3.md)
**Last Verified**: 2025-11-21
**Attribution**: Content derived from [SAP API Style Guide](https://github.com/SAP-docs/api-style-guide) (Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/))
**Changes**: Consolidated from multiple source files, reorganized for progressive disclosure, added examples and templates.
---
## Table of Contents
1. [Overview](#overview)
2. [API Lifecycle States](#api-lifecycle-states)
3. [Timeline Requirements](#timeline-requirements)
4. [Required Metadata](#required-metadata)
5. [Stakeholder Responsibilities](#stakeholder-responsibilities)
6. [Deprecation Process](#deprecation-process)
7. [Decommission Process](#decommission-process)
8. [Best Practices](#best-practices)
9. [Examples](#examples)
---
## Overview
### Core Definition
A **deprecated API** "is no longer supported in future releases, and therefore not encouraged for use."
A **decommissioned API** has been fully retired and cannot be used in production.
### Key Principles
1. **Transparency**: Clearly communicate API lifecycle state to consumers
2. **Predictability**: Provide adequate notice before decommissioning
3. **Support**: Maintain deprecated APIs for minimum periods
4. **Documentation**: Update all documentation to reflect current state
5. **Migration Guidance**: Provide clear paths to successor APIs
---
## API Lifecycle States
SAP APIs use the `x-sap-stateInfo` attribute to define four lifecycle states:
### 1. Beta
**Definition**: Pre-production testing phase
**Characteristics**:
- Available for testing and evaluation
- May have incompatible changes without notice
- Not recommended for production use
- No support guarantees
**Use Case**: Early adopters testing new functionality
**Metadata**:
```yaml
x-sap-stateInfo:
state: beta
```
### 2. Active
**Definition**: Live production-ready APIs
**Characteristics**:
- Fully supported for production use
- Backward compatibility maintained
- Default status (can be omitted from metadata)
- Full support and SLAs apply
**Use Case**: Standard production API usage
**Metadata**:
```yaml
x-sap-stateInfo:
state: active
```
Or simply omit the attribute (active is default).
### 3. Deprecated
**Definition**: Live but replaced by an active successor
**Characteristics**:
- Still functional and supported (temporarily)
- Not recommended for new implementations
- Requires migration to successor API
- Support period defined (minimum 12 months)
- Must include deprecation date and successor information
**Use Case**: Legacy APIs being phased out
**Metadata**:
```yaml
x-sap-stateInfo:
state: deprecated
deprecationDate: "2024-01-15"
successorApi: "NewAPIName v2.0"
```
### 4. Decommissioned
**Definition**: Retired from production
**Characteristics**:
- No longer functional
- Cannot be used in any environment
- Removed from documentation
- No support available
**Use Case**: Fully retired APIs
**Implementation**: Remove from artifact or mark in changelog
---
## Timeline Requirements
### Minimum Support Period After Deprecation
**12 months minimum** support period after deprecation announcement
**Calculation**:
- Starts from deprecation announcement date
- Continues until decommission date
- Allows customers adequate migration time
**Example Timeline**:
```
Jan 15, 2024: API deprecated (announcement)
Jan 15, 2025: Earliest decommission date (12 months later)
```
### Minimum Total Lifespan
**24 months minimum** total lifespan in active or deprecated status before decommissioning
**Calculation**:
- Starts from initial active release
- Includes time in active state + time in deprecated state
- Ensures reasonable API stability
**Example Timeline**:
```
Jan 1, 2022: API released (active)
Jan 1, 2024: API deprecated (24 months active)
Jan 1, 2025: Earliest decommission (12 months deprecated)
Alternative:
Jan 1, 2022: API released (active)
Jun 1, 2022: API deprecated (6 months active)
Jun 1, 2024: Earliest decommission (18 months deprecated, 24 total)
```
### Best Practice Timeline
SAP recommends:
- **Active period**: 18-36 months before deprecation
- **Deprecation period**: 12-24 months before decommission
- **Total lifespan**: 30+ months for production APIs
---
## Required Metadata
### OpenAPI Specification
APIs must include `x-sap-stateInfo` object in the OpenAPI specification file:
```yaml
openapi: 3.0.0
info:
title: Employee Management API
version: 1.5.0
x-sap-stateInfo:
state: deprecated
deprecationDate: "2024-01-15"
successorApi: "Employee Management API v2.0"
```
**Required Fields for Deprecated APIs**:
- `state`: Must be "deprecated"
- `deprecationDate`: ISO 8601 date format (YYYY-MM-DD)
- `successorApi`: Name and version of replacement API
### Artifact.json
APIs must include changelog entries in `artifact.json`:
```json
{
"changelog": [
{
"state": "deprecated",
"date": "2024-01-15",
"version": "1.5.0",
"notes": "Deprecated in favor of Employee Management API v2.0. Migration guide available at [https://help.sap.com/migration-guide"](https://help.sap.com/migration-guide")
},
{
"state": "active",
"date": "2022-01-01",
"version": "1.0.0",
"notes": "Initial release"
}
]
}
```
**Required Fields**:
- `state`: Current API state
- `date`: State change date (ISO 8601 format)
- `version`: API version at state change
- `notes`: Descriptive information about the change
---
## Stakeholder Responsibilities
### Product Owners
**Lifecycle Decisions**:
- Determine when to deprecate APIs
- Decide deprecation timelines
- Identify successor APIs
- Approve decommission schedules
**Metadata Configuration**:
- Ensure `x-sap-stateInfo` properly configured
- Maintain accurate `artifact.json` changelog
- Verify metadata consistency across systems
**Communication**:
- Announce deprecation through release notes
- Publish blog posts about major deprecations
- Notify affected customers directly
- Provide migration timelines
**Support Management**:
- Maintain support during deprecation period
- Allocate resources for customer migration assistance
- Track migration progress
- Coordinate decommission activities
### UA (User Assistance) Developers
**Documentation Updates**:
- Add deprecation notices to API documentation
- Update API reference pages with warnings
- Create prominent deprecation banners
- Link to successor API documentation
**Decommission Documentation**:
- Remove links to decommissioned APIs
- Archive old documentation appropriately
- Redirect old URLs to successor documentation
- Update navigation and search indices
**Source Code Tags**:
- Apply `@deprecated` tag in Javadoc/JSDoc comments
- Include deprecation reason and alternative
- Update inline documentation
- Add migration code examples
**Migration Guidance**:
- Create migration guides in release notes
- Document API differences
- Provide code migration examples
- Publish before-and-after comparisons
### Development Teams
**Code Maintenance**:
- Continue bug fixes during deprecation period
- Maintain security patches
- No new feature development
- Plan removal timeline
**Testing**:
- Maintain test coverage during deprecation
- Test successor API thoroughly
- Validate migration paths
- Monitor customer usage patterns
---
## Deprecation Process
### Step 1: Decision and Planning
1. **Assess API Usage**:
- Review usage metrics and analytics
- Identify affected customers
- Estimate migration effort
2. **Define Successor**:
- Identify replacement API
- Document migration path
- Create migration guide
3. **Set Timeline**:
- Calculate minimum support period (12 months)
- Verify total lifespan requirement (24 months)
- Set deprecation and decommission dates
### Step 2: Update Metadata
1. **OpenAPI Specification**:
```yaml
x-sap-stateInfo:
state: deprecated
deprecationDate: "2024-01-15"
successorApi: "NewAPI v2.0"
```
2. **Artifact.json**:
```json
{
"changelog": [{
"state": "deprecated",
"date": "2024-01-15",
"version": "1.5.0",
"notes": "Deprecated. Use NewAPI v2.0. Migration guide: [https://..."](https://...")
}]
}
```
3. **Source Code** (Java example):
```java
/**
* Gets customer address.
*
* @deprecated As of version 1.5.0, replaced by
* {@link com.sap.newapi.Customer#getAddress()}
* Use the new API which provides enhanced address validation.
*/
@Deprecated
public Address getCustomerAddress() {
// implementation
}
```
### Step 3: Documentation Updates
1. **API Reference**:
- Add deprecation banner at top of page
- Include deprecation date and successor
- Link to migration guide
2. **Release Notes**:
- Announce deprecation
- Explain reason for deprecation
- Provide migration timeline
- Link to migration guide
3. **Migration Guide**:
- Document API differences
- Provide code examples
- Explain migration steps
- List breaking changes
### Step 4: Communication
1. **Announcement Channels**:
- Release notes
- Blog posts
- Email to affected customers
- In-app notifications (if applicable)
2. **Announcement Content**:
- What is being deprecated
- Why it's being deprecated
- When it will be decommissioned
- What to use instead
- Where to find migration guidance
### Step 5: Support Period
1. **Maintain Support**:
- Continue bug fixes
- Provide security patches
- Answer customer questions
- Monitor migration progress
2. **Track Migration**:
- Monitor API usage metrics
- Identify customers still using deprecated API
- Proactively contact stragglers
- Offer migration assistance
---
## Decommission Process
### Prerequisites
Before decommissioning, verify:
- [ ] Minimum 12 months since deprecation announcement
- [ ] Minimum 24 months total lifespan
- [ ] All customers notified
- [ ] Migration guidance published
- [ ] Successor API available and stable
- [ ] Remaining usage is minimal
### Decommission Methods
#### Method 1: Remove Entire API Package
**For complete API removal**:
1. Delete artifact folder from repository
2. Commit and push changes
3. Republish to SAP API Business Hub (API will be removed)
**Example**:
```bash
# Remove the API directory
rm -rf apis/EmployeeManagement/1.0
# Commit removal
git add -A
git commit -m "Decommission EmployeeManagement API v1.0"
git push
```
#### Method 2: Remove Specific Endpoints
**For partial API removal**:
1. Edit `artifact.json`
2. Remove specific endpoint definitions
3. Update changelog with decommission notice
4. Commit and push changes
**Example** (`artifact.json`):
```json
{
"changelog": [
{
"state": "decommissioned",
"date": "2025-01-15",
"version": "1.5.0",
"notes": "Endpoint /legacy/customers decommissioned. Use /v2/customers instead."
}
],
"paths": {
"/v2/customers": { ... }
// Removed: "/legacy/customers"
}
}
```
### Post-Decommission Actions
1. **Documentation Cleanup**:
- Remove API from documentation site
- Archive old documentation
- Set up redirects to successor API
- Update navigation menus
2. **URL Management**:
- Configure HTTP 410 (Gone) responses for old endpoints
- Include message pointing to successor API
- Maintain redirects for reasonable period
3. **Communication**:
- Publish decommission announcement
- Send final notification to any remaining users
- Update status pages
---
## Best Practices
### Planning
1. **Early Assessment**: Evaluate deprecation candidates during product planning
2. **Customer Impact**: Always consider customer migration effort
3. **Batch Deprecations**: Group related API deprecations together
4. **Version Strategy**: Use semantic versioning to signal breaking changes
### Communication
1. **Multiple Channels**: Announce through all available channels
2. **Advance Notice**: Provide notice well before minimum period
3. **Clear Messaging**: Explain what, why, when, and how
4. **Regular Reminders**: Send periodic reminders during deprecation period
### Documentation
1. **Prominent Warnings**: Make deprecation notices highly visible
2. **Complete Migration Guides**: Don't just say "use X instead" - explain how
3. **Code Examples**: Provide before/after code comparisons
4. **FAQs**: Answer common migration questions
### Technical
1. **Graceful Degradation**: Consider warning headers before hard removal
2. **Usage Tracking**: Monitor deprecated API usage
3. **Migration Tools**: Provide automated migration tools when feasible
4. **Backward Compatibility**: Maintain during deprecation period
---
## Examples
### Example 1: REST API Endpoint Deprecation
**OpenAPI Specification**:
```yaml
openapi: 3.0.0
info:
title: Order Management API
version: 2.1.0
paths:
/orders/{orderId}:
get:
summary: Get order details
deprecated: true
description: |
**DEPRECATED**: This endpoint is deprecated as of January 15, 2024.
Use /v2/orders/{orderId} instead.
This endpoint will be decommissioned on January 15, 2025.
Migration guide: [https://help.sap.com/order-api-migration](https://help.sap.com/order-api-migration)
x-sap-stateInfo:
state: deprecated
deprecationDate: "2024-01-15"
successorApi: "/v2/orders/{orderId}"
responses:
'200':
description: Order details (deprecated)
headers:
Warning:
schema:
type: string
description: '299 - "Deprecated API. Use /v2/orders/{orderId}"'
```
### Example 2: Java Method Deprecation
```java
/**
* Service for managing customer data.
*/
public class CustomerService {
/**
* Retrieves customer by ID.
*
* @param customerId the customer identifier
* @return customer object
* @throws NotFoundException if customer not found
* @deprecated As of version 2.0.0 (deprecated January 15, 2024),
* replaced by {@link #getCustomerById(String)}
* The new method provides enhanced validation and
* supports additional customer types.
* This method will be removed in version 3.0.0
* (scheduled for January 15, 2025).
* Migration guide: [https://help.sap.com/customer-api-migration](https://help.sap.com/customer-api-migration)
*/
@Deprecated(since = "2.0.0", forRemoval = true)
public Customer getCustomer(int customerId) throws NotFoundException {
// Legacy implementation
return legacyCustomerRetrieval(customerId);
}
/**
* Retrieves customer by ID with enhanced validation.
*
* @param customerId the customer identifier (supports all formats)
* @return customer object
* @throws NotFoundException if customer not found
* @throws ValidationException if customerId format invalid
* @since 2.0.0
*/
public Customer getCustomerById(String customerId)
throws NotFoundException, ValidationException {
// New implementation
return enhancedCustomerRetrieval(customerId);
}
}
```
### Example 3: Complete API Deprecation Timeline
**Timeline**: Document Management API
```
2022-01-01: API v1.0.0 released (active)
├─ State: active
├─ Full support and SLAs
└─ Production-ready
2023-06-15: API v2.0.0 released
├─ Enhanced features
├─ Better performance
└─ v1.0.0 remains active
2024-01-15: API v1.0.0 deprecated
├─ State: deprecated
├─ Deprecation announcement published
├─ Migration guide released
├─ Support continues
└─ x-sap-stateInfo updated
2024-07-15: 6-month reminder
├─ Email to remaining v1.0.0 users
├─ 6 months until decommission
└─ Migration assistance offered
2024-10-15: 3-month reminder
├─ Final migration push
├─ Direct contact to high-usage customers
└─ Migration tools provided
2025-01-15: API v1.0.0 decommissioned
├─ State: decommissioned
├─ Endpoints return HTTP 410 Gone
├─ Documentation removed
├─ Redirects to v2.0.0 documentation
└─ Final announcement published
Total Timeline:
- Active period: 24 months (Jan 2022 - Jan 2024)
- Deprecated period: 12 months (Jan 2024 - Jan 2025)
- Total lifespan: 36 months ✓ (exceeds 24-month minimum)
- Support after deprecation: 12 months ✓ (meets minimum)
```
---
## Reference
### External Standards
- **OpenAPI Specification**: [https://spec.openapis.org/oas/latest.html](https://spec.openapis.org/oas/latest.html)
- **Semantic Versioning**: [https://semver.org/](https://semver.org/)
- **HTTP Status Codes**: [https://httpstatuses.com/](https://httpstatuses.com/)
### SAP Resources
- **SAP API Business Hub**: [https://api.sap.com/](https://api.sap.com/)
- **SAP Help Portal**: [https://help.sap.com/](https://help.sap.com/)
### Related Documentation
- API Naming Guidelines
- API Quality Checklist
- API Review Process
- Developer Guide Standards
---
**Document Version**: 1.0.0
**Last Updated**: 2025-11-21
**Maintainer**: SAP Skills Team | [https://github.com/secondsky/sap-skills](https://github.com/secondsky/sap-skills)

View File

@@ -0,0 +1,704 @@
# Developer and Service Guides
**Source**: [https://github.com/SAP-docs/api-style-guide/tree/main/docs/60-developer-or-service-guide](https://github.com/SAP-docs/api-style-guide/tree/main/docs/60-developer-or-service-guide)
**Last Verified**: 2025-11-21
**Attribution**: Content derived from [SAP API Style Guide](https://github.com/SAP-docs/api-style-guide) (Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/))
**Changes**: Consolidated from multiple source files, reorganized for progressive disclosure, added examples and templates.
---
## Table of Contents
1. [Overview](#overview)
2. [Purpose and Scope](#purpose-and-scope)
3. [Content Structure Guidelines](#content-structure-guidelines)
4. [Topic Types and Conventions](#topic-types-and-conventions)
5. [Content Selection Guidelines](#content-selection-guidelines)
6. [Code Sample Standards](#code-sample-standards)
7. [Best Practices](#best-practices)
8. [Examples](#examples)
---
## Overview
Developer and service guides are supplementary resources that explain how to use APIs, SDKs, and development platforms alongside API references.
### Relationship to API Reference Documentation
| Documentation Type | Purpose | Content |
|-------------------|---------|---------|
| **API Reference** | Technical specification | Auto-generated docs, parameters, responses, methods |
| **Developer Guide** | Practical usage | Concepts, tutorials, scenarios, best practices |
**Key Principle**: Developer guides complement API references by providing context, examples, and practical guidance that cannot be auto-generated.
---
## Purpose and Scope
### What Developer Guides Include
1. **Conceptual Information**
- Goal, scope, and capabilities of an API
- Architectural diagrams explaining API structure
- System context and integration points
- Business scenarios and use cases
2. **Code Quality Practices**
- Secure programming guidelines
- Resilience patterns and error handling
- Performance optimization techniques
- Best practices for API consumption
3. **Access & Setup**
- Security requirements and authentication
- Initial setup and configuration
- Environment preparation
- Prerequisites and dependencies
4. **Practical Usage**
- Typical tasks and scenarios
- Workflows combining multiple API calls
- Sample code and tutorials
- Common integration patterns
### Variability Across Products
Developer guides vary significantly in:
- **Scope**: From single API to entire platform
- **Complexity**: From simple tutorials to comprehensive system documentation
- **Depth**: From quick-start guides to architectural deep-dives
- **Audience**: From beginners to advanced developers
**Important Note**: Due to this variability, a one-size-fits-all standard is impractical. These guidelines provide flexible frameworks that technical writers adapt based on product needs and target audience.
---
## Content Structure Guidelines
### Fundamental Information Design
Developer guides should follow these structural principles:
1. **Separation by Type**
- Separate chapters for **concepts**, **tasks**, and **reference** material
- Clear boundaries between information types
- Logical progression from concepts → tasks → reference
2. **Task-Oriented Approach**
- Enable rapid developer task completion
- Focus on practical outcomes
- "How do I...?" questions should be easily answerable
3. **Consistent Title Conventions**
- Use standardized titling patterns (see Topic Types below)
- Maintain consistency throughout documentation
- Make topics easily scannable
---
## Topic Types and Conventions
### Topic Type Matrix
| Type | Purpose | Title Format | Example | Content |
|------|---------|--------------|---------|---------|
| **Concept** | Introductions, overviews, background information | Noun phrase | "SAP HANA Cloud", "OAuth 2.0 Authentication" | Explains what something is, why it matters, how it works |
| **Reference** | API documentation, tables, specifications, syntax | Noun phrase | "SAP HANA Cloud JavaScript Reference", "API Endpoints" | Lists methods, parameters, configuration options |
| **Complex Task** | Tutorials, multi-step procedures with code | Gerund phrase (-ing) | "Developing SAP HANA Cloud Applications", "Building a Fiori App" | Step-by-step tutorials with code samples |
| **Detailed Task** | Single tasks with code samples | Gerund phrase (-ing) | "Creating an Application Project", "Configuring OAuth" | Specific how-to instructions |
### Title Examples by Type
**Concept Topics**:
- ✅ "API Authentication Overview"
- ✅ "Understanding OData Query Options"
- ✅ "SAP Cloud Platform Architecture"
- ❌ "How to Understand OAuth" (task format for concept)
**Reference Topics**:
- ✅ "Environment Variables Reference"
- ✅ "Configuration Parameters"
- ✅ "Error Code Catalog"
- ❌ "Configuring Environment Variables" (task format for reference)
**Task Topics**:
- ✅ "Implementing OAuth 2.0 Authentication"
- ✅ "Creating Your First API Request"
- ✅ "Deploying to Cloud Foundry"
- ❌ "OAuth Implementation" (noun phrase for task)
---
## Content Selection Guidelines
### Collaborate with Product Owners
**Key Principle**: "Don't try to cover all of the APIs in your product."
Work with product teams to:
1. **Identify Priority APIs**: Focus on most commonly used or business-critical APIs
2. **Define Key Use Cases**: Document typical scenarios, not every possibility
3. **Target Audience Needs**: Write for your primary developer persona
4. **Balance Coverage vs. Depth**: Deep coverage of important topics beats shallow coverage of everything
### Content Scope Decisions
#### Include:
- ✅ Customer-relevant information
- ✅ Business scenarios and use cases
- ✅ Integration patterns and workflows
- ✅ Authentication and security guidance
- ✅ Error handling patterns
- ✅ Performance best practices
- ✅ Migration guides for version changes
#### Exclude:
- ❌ Internal implementation details
- ❌ Duplicate SAP API Business Hub information
- ❌ Every possible API method (focus on common ones)
- ❌ Internal architecture not relevant to consumers
- ❌ Debugging information for SAP internal teams
### Depth vs. Breadth
**Guideline**: "Don't write a novel, keep the topics short and concise."
- **Short Topics**: 300-800 words for most topics
- **Long Tutorials**: 1000-2000 words maximum
- **Complex Topics**: Break into smaller, manageable subtopics
- **Progressive Disclosure**: Link to detailed information rather than including everything
### Diagram Guidelines
**Use Clear Diagrams**:
- Avoid excessive complexity
- Remove internal-only information
- Adapt internal architectural diagrams for external audiences
- Focus on customer-relevant flows and interactions
**Avoid Redundancy**:
- Don't duplicate diagrams unnecessarily
- Use one clear diagram instead of multiple similar ones
- Reference existing diagrams when appropriate
---
## Code Sample Standards
### Quality Requirements
All code samples must meet these criteria:
#### 1. Compilable Without Errors
**Requirement**: "Must compile without errors"
- Test all code before publication
- Verify with actual compiler/interpreter
- Include necessary imports and dependencies
- Handle version-specific syntax
**Bad Example** ❌:
```java
// This won't compile - missing imports
Customer customer = getCustomer();
```
**Good Example** ✅:
```java
import com.sap.customer.Customer;
import com.sap.customer.CustomerService;
CustomerService service = new CustomerService();
Customer customer = service.getCustomer("12345");
```
#### 2. Concise and Focused
**Requirement**: "Concise, containing only API-relevant code"
- Show only code necessary to demonstrate the concept
- Remove boilerplate unrelated to the API
- Focus on the API call itself and essential context
**Bad Example** ❌:
```java
public class CustomerExample {
private static final Logger logger = LogManager.getLogger();
private Configuration config;
private MetricsCollector metrics;
public CustomerExample() {
this.config = new Configuration();
this.metrics = new MetricsCollector();
logger.info("Initializing example...");
}
public void demonstrateAPI() {
logger.debug("Starting API call");
metrics.startTimer();
try {
// Actual API usage buried in boilerplate
Customer customer = api.getCustomer("12345");
logger.debug("Customer retrieved: " + customer.getName());
} catch (Exception e) {
logger.error("Failed", e);
metrics.recordError();
} finally {
metrics.stopTimer();
}
}
}
```
**Good Example** ✅:
```java
// Get a customer by ID
Customer customer = api.getCustomer("12345");
System.out.println("Customer: " + customer.getName());
// Error handling
try {
customer = api.getCustomer("invalid");
} catch (NotFoundException e) {
System.out.println("Customer not found");
}
```
#### 3. Sufficient Comments
**Requirement**: "Include sufficient comments for clarity"
- Explain **why**, not just **what**
- Comment complex logic or API-specific requirements
- Don't over-comment obvious code
**Bad Example** ❌:
```java
// Create customer service
CustomerService service = new CustomerService();
// Get customer
Customer customer = service.getCustomer("12345");
// Print customer name
System.out.println(customer.getName());
```
**Good Example** ✅:
```java
// Initialize service with default authentication
CustomerService service = new CustomerService();
// Retrieve customer by SAP customer number
// Note: Customer ID must be numeric string format
Customer customer = service.getCustomer("12345");
// Display full legal name (formatted by locale)
System.out.println(customer.getName());
```
#### 4. Easy Copy-Paste
**Requirement**: "Enable easy copy-paste into code editors"
- Use standard formatting (not proprietary)
- Include necessary context (imports, variables)
- Avoid line breaks in strings when possible
- Use consistent indentation
**Bad Example** ❌:
```java
Customer customer = api.
getCustomer(
"12345"
); // Awkward formatting
```
**Good Example** ✅:
```java
Customer customer = api.getCustomer("12345");
```
### Code Sample Patterns
#### Pattern 1: Basic API Call
```javascript
// Simple GET request example
const response = await fetch('[https://api.sap.com/customers/12345',](https://api.sap.com/customers/12345',) {
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json'
}
});
const customer = await response.json();
console.log(customer);
```
#### Pattern 2: Error Handling
```java
try {
Customer customer = service.getCustomer(customerId);
processCustomer(customer);
} catch (NotFoundException e) {
// Customer doesn't exist - handle gracefully
logger.warn("Customer not found: " + customerId);
return Optional.empty();
} catch (UnauthorizedException e) {
// Authentication failed - refresh token
refreshAuthToken();
return getCustomerWithRetry(customerId);
}
```
#### Pattern 3: Complete Workflow
```python
# Complete workflow: Authenticate, retrieve, update customer
# Step 1: Authenticate
auth_token = authenticate(api_key, secret)
# Step 2: Retrieve customer data
customer = api.get_customer(
customer_id="12345",
auth_token=auth_token
)
# Step 3: Update customer information
customer['email'] = 'new.email@example.com'
# Step 4: Save changes
result = api.update_customer(
customer_id="12345",
data=customer,
auth_token=auth_token
)
print(f"Update successful: {result['status']}")
```
---
## Best Practices
### 1. Progressive Learning
Structure content for developers at different skill levels:
**Beginner Level**:
- Quick start guides
- Simple, complete examples
- Step-by-step tutorials
- Heavy use of code samples
**Intermediate Level**:
- Common integration patterns
- Best practices
- Error handling strategies
- Performance optimization
**Advanced Level**:
- Complex workflows
- Custom extensions
- Advanced configuration
- Architecture patterns
### 2. Practical Focus
**Emphasize**:
- Real-world scenarios
- Working code examples
- Common pitfalls and solutions
- Typical workflows
**De-emphasize**:
- Theoretical concepts without application
- Every possible parameter combination
- Rarely-used features
- Internal implementation details
### 3. Tutorial Format for Complex Tasks
For complex multi-step processes:
1. **Break into Smaller Subtopics**: Each subtopic covers one logical step
2. **Clear Prerequisites**: State what readers need before starting
3. **Expected Outcomes**: Show what success looks like
4. **Troubleshooting**: Include common issues and solutions
**Example Structure**:
```
Tutorial: Building Your First Fiori Application
├── Prerequisites
│ ├── Required tools
│ ├── Account setup
│ └── Sample data
├── Part 1: Creating the Project
│ ├── Initialize project
│ ├── Configure manifest
│ └── Verify setup
├── Part 2: Building the UI
│ ├── Create view
│ ├── Add controls
│ └── Test locally
├── Part 3: Adding Data Binding
│ ├── Configure OData service
│ ├── Bind to controls
│ └── Test with real data
├── Part 4: Deployment
│ ├── Build for production
│ ├── Deploy to Cloud
│ └── Verify deployment
└── Troubleshooting
├── Common build errors
├── Connection issues
└── Getting help
```
### 4. Avoid Duplication with API Business Hub
**Don't Duplicate**:
- ❌ API endpoint listings (available in API Business Hub)
- ❌ Parameter descriptions (auto-generated)
- ❌ Response schema definitions
**Do Provide**:
- ✅ Deeper analysis of when to use which endpoint
- ✅ Integration patterns combining multiple endpoints
- ✅ Business context for API usage
- ✅ Migration guides and version comparisons
### 5. Maintain and Update
- **Regular Reviews**: Update guides when APIs change
- **Version Notices**: Clearly indicate which API version guide applies to
- **Deprecation Warnings**: Mark outdated content prominently
- **Feedback Loops**: Collect and incorporate developer feedback
---
## Examples
### Example 1: Concept Topic
**Title**: "Understanding SAP OAuth 2.0 Authentication"
**Structure**:
```markdown
# Understanding SAP OAuth 2.0 Authentication
## What is OAuth 2.0?
OAuth 2.0 is an authorization framework that enables applications
to obtain limited access to user accounts on SAP services.
## Why Use OAuth 2.0?
- **Security**: Never expose user passwords to third-party applications
- **Limited Access**: Grant specific permissions, not full account access
- **Revocable**: Users can revoke access anytime
- **Standard**: Industry-standard protocol supported across SAP services
## How It Works
[Diagram: OAuth 2.0 Flow]
1. Application requests authorization
2. User grants permission
3. Application receives access token
4. Application uses token to access resources
## Grant Types
SAP supports three OAuth 2.0 grant types:
### Authorization Code (Recommended)
Best for server-side web applications...
### Client Credentials
Best for machine-to-machine communication...
### Refresh Token
Used to obtain new access tokens...
## Next Steps
- [Implementing OAuth 2.0 Authentication](#) (Task Guide)
- [OAuth Configuration Reference](#) (Reference)
```
### Example 2: Task Topic
**Title**: "Implementing OAuth 2.0 Client Credentials Flow"
**Structure**:
```markdown
# Implementing OAuth 2.0 Client Credentials Flow
This guide shows how to implement OAuth 2.0 authentication using
the Client Credentials grant type for server-to-server communication.
## Prerequisites
- SAP BTP account
- OAuth client ID and secret
- Node.js 14+ installed
## Step 1: Obtain Client Credentials
1. Log in to SAP BTP Cockpit
2. Navigate to Security → OAuth Clients
3. Click "Create New Client"
4. Copy client ID and secret
## Step 2: Request Access Token
```javascript
const fetch = require('node-fetch');
async function getAccessToken() {
const credentials = Buffer.from(
`${CLIENT_ID}:${CLIENT_SECRET}`
).toString('base64');
const response = await fetch('[https://auth.sap.com/oauth/token',](https://auth.sap.com/oauth/token',) {
method: 'POST',
headers: {
'Authorization': `Basic ${credentials}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&scope=read write'
});
const data = await response.json();
return data.access_token;
}
```
## Step 3: Use Token for API Requests
```javascript
async function callAPI() {
const token = await getAccessToken();
const response = await fetch('[https://api.sap.com/resource',](https://api.sap.com/resource',) {
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
```
## Step 4: Handle Token Expiration
Tokens expire after 1 hour. Implement token refresh:
```javascript
let cachedToken = null;
let tokenExpiry = null;
async function getValidToken() {
const now = Date.now();
// Return cached token if still valid
if (cachedToken && tokenExpiry > now) {
return cachedToken;
}
// Request new token
cachedToken = await getAccessToken();
tokenExpiry = now + (3600 * 1000); // 1 hour
return cachedToken;
}
```
## Troubleshooting
### "Invalid client credentials"
- Verify client ID and secret are correct
- Ensure credentials are base64 encoded properly
### "Insufficient scope"
- Check that your OAuth client has required scopes
- Request appropriate scopes in token request
## Next Steps
- [OAuth 2.0 Best Practices](#)
- [Authorization Code Flow](#)
- [Token Management Strategies](#)
```
### Example 3: Reference Topic
**Title**: "OAuth Configuration Parameters"
**Structure**:
```markdown
# OAuth Configuration Parameters
Complete reference for OAuth 2.0 configuration options.
## Token Endpoint
**URL**: `[https://auth.sap.com/oauth/token`](https://auth.sap.com/oauth/token`)
## Request Parameters
| Parameter | Required | Description | Example |
|-----------|----------|-------------|---------|
| `grant_type` | Yes | OAuth grant type | `client_credentials` |
| `client_id` | Yes | OAuth client identifier | `sb-client-12345` |
| `client_secret` | Yes | OAuth client secret | `abc123...` |
| `scope` | No | Requested permissions | `read write` |
## Response Format
```json
{
"access_token": "eyJhbGc...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "read write"
}
```
## Error Codes
| Code | Description | Resolution |
|------|-------------|------------|
| `invalid_client` | Invalid credentials | Verify client ID/secret |
| `invalid_grant` | Grant type not supported | Use supported grant type |
| `invalid_scope` | Scope not available | Request valid scopes |
```
---
## Reference
### SAP Resources
- **SAP Help Portal**: [https://help.sap.com/](https://help.sap.com/)
- **SAP API Business Hub**: [https://api.sap.com/](https://api.sap.com/)
- **SAP Community**: [https://community.sap.com/](https://community.sap.com/)
### Related Documentation
- API Reference Documentation Standards
- API Quality Checklist
- Code Sample Guidelines
---
**Document Version**: 1.0.0
**Last Updated**: 2025-11-21
**Maintainer**: SAP Skills Team | [https://github.com/secondsky/sap-skills](https://github.com/secondsky/sap-skills)

View File

@@ -0,0 +1,472 @@
# Glossary and External Resources
**Source**: [https://github.com/SAP-docs/api-style-guide/](https://github.com/SAP-docs/api-style-guide/)
**Last Verified**: 2025-11-21
**Attribution**: Content derived from [SAP API Style Guide](https://github.com/SAP-docs/api-style-guide) (Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/))
**Changes**: Consolidated from multiple source files, reorganized for progressive disclosure, added examples and templates.
---
## Table of Contents
1. [Glossary](#glossary)
2. [External Resources](#external-resources)
3. [SAP-Specific Resources](#sap-specific-resources)
4. [Quick Reference](#quick-reference)
---
## Glossary
### A
**API (Application Programming Interface)**
An interface provided by an application for interacting with other applications. Enables software programs to exchange information across organizational boundaries by selectively exposing functionality.
**API Documentation Comment**
Combines descriptions and block tags in source code for generating API reference documentation. Used by documentation generators like Javadoc, JSDoc, and Doxygen.
**API Documentation Generators**
Tools like Javadoc, JSDoc, Doxygen, and Swagger that extract comments from source code and produce structured documentation.
### C
**Code Sample File**
A complete, working example demonstrating API features that ships with SDKs. More comprehensive than code snippets, showing real-world implementation patterns.
**Code Snippet**
Several lines of code illustrating API method usage. Typically embedded in documentation to demonstrate specific functionality.
**Component (OpenAPI)**
Reusable object definitions in OpenAPI Specification 3.0+ (called "Definitions" in version 2.0). Includes schemas, parameters, responses, examples, etc.
### D
**Decommissioned**
APIs that have been fully retired and cannot be used in production. Final state in API lifecycle.
**Definition (OpenAPI)**
See **Component**. Term used in OpenAPI Specification 2.0 for reusable objects.
**Demo Application**
A basic implementation provided with SDKs showing main API capabilities and typical usage patterns.
**Deprecated**
API elements no longer supported in future releases, marked with the `x-sap-stateInfo` attribute or `@deprecated` tag. Not encouraged for use but still functional.
**Documentation Tag**
Special marker instructing documentation generators how to format comment sections. Examples: `@param`, `@return`, `<summary>`, `\file`.
### E
**Entity (OData)**
Typed data object in OData Entity Data Model (EDM). Examples: Customer, Employee, Order.
**Entity Data Model (EDM)**
Structured data description in OData protocol defining entities, entity sets, relationships, and operations.
**Entity Set (OData)**
Named collection of entities. Example: "Customers" is an entity set containing Customer entities.
**Exception**
Documented errors occurring during method execution, typically using `@throws`, `@exception`, or `<exception>` tags.
### M
**Metadata (OData)**
XML document describing the structure of an OData service. Accessible at `$metadata` endpoint (e.g., `[https://api.sap.com/odata/$metadata](https://api.sap.com/odata/$metadata)`).
### O
**OData (Open Data Protocol)**
A REST-based protocol for querying and updating data, built on HTTP, Atom/XML, and JSON standards. Maintained by OASIS Open.
**Operation (REST/OData)**
HTTP method (GET, PUT, POST, DELETE, PATCH) for manipulating endpoints or performing actions on resources.
**OpenAPI Specification**
Community-driven open specification for RESTful APIs under the OpenAPI Initiative. Version 3.0.3 is current standard.
### P
**Parameter**
Option passed with a path, such as filtering criteria, sorting options, or pagination controls. Can appear in path, query, header, body, or formData.
**Partner APIs**
APIs created by SAP partners for customers, published on the SAP API Business Hub.
**Path (REST/OData)**
Endpoint or resource in API URLs. Examples: `/users`, `/users/{id}`, `/orders/{orderId}/items`.
**Private APIs**
APIs restricting access to vendors, partners, or selected customers. Not publicly available.
**Public APIs**
APIs available in the public domain that become vendor-client contracts. Require careful versioning and deprecation management.
### R
**Resource (REST/OData)**
Concept or object that users want to control through HTTP requests. Identified by URIs and manipulated using HTTP methods.
**Response**
HTTP status code combined with outcome description, optionally including response body with data or error information.
**REST API (Representational State Transfer)**
Architectural style enabling cross-platform CRUD operations over HTTP. Focuses on resources rather than actions.
**Return Type/Value**
Data returned by methods, documented using `@return`, `@returns`, or `<returns>` tags.
### S
**Schema (OpenAPI)**
Data structure definition describing request/response formats. Defines properties, types, required fields, and validation rules.
**SPI (Service Provider Interface)**
Vendor-defined interface intended for third-party implementation, extending or customizing API functionality.
### X
**x-sap-stateInfo**
SAP-specific OpenAPI extension attribute defining API lifecycle state: beta, active, deprecated, or decommissioned.
---
## External Resources
### API Standards & Specifications
#### OpenAPI Specification
**URL**: [https://spec.openapis.org/oas/latest.html](https://spec.openapis.org/oas/latest.html)
**Description**: The standard for RESTful APIs. A community-driven open specification within the OpenAPI Initiative for describing HTTP APIs in a machine-readable format.
**Use For**:
- REST API specification structure
- OpenAPI document format
- API schema definitions
- Operation documentation
**Current Version**: 3.0.3 (3.1.0 available)
#### OData Specification
**URL**: [https://www.odata.org/documentation/](https://www.odata.org/documentation/)
**Description**: The standard for OData maintained by OASIS Open. Defines protocol for querying and updating data over HTTP.
**Use For**:
- OData service structure
- EDM (Entity Data Model) design
- Query operation syntax
- OData conventions
**Supported Versions**: 4.01, 3.0, 2.0
### Documentation Tools
#### Java - Javadoc
**URL**: [https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)
**Description**: Oracle's guidance on "How to Write Doc Comments for the Javadoc Tool" through their Technology Network.
**Use For**:
- Java API documentation
- Javadoc tag reference
- Documentation comment format
- Tool usage and configuration
**Official Oracle Reference**: [https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html)
#### JavaScript - JSDoc
**URL**: [https://jsdoc.app/](https://jsdoc.app/)
**Description**: JSDoc 3 documentation generator available on GitHub. Comprehensive tag reference and examples.
**Use For**:
- JavaScript API documentation
- JSDoc tag syntax
- TypeScript documentation
- Node.js project documentation
**Tag Reference**: [https://jsdoc.app/index.html#block-tags](https://jsdoc.app/index.html#block-tags)
**Markdown Support**: [https://jsdoc.app/about-including-markdown.html](https://jsdoc.app/about-including-markdown.html)
#### Microsoft .NET
**C# XML Documentation**
**URL**: [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/)
**Description**: Microsoft's official guidance for C# XML documentation comments.
**Use For**:
- .NET API documentation
- XML comment syntax
- Visual Studio integration
- IntelliSense support
**.NET Naming Guidelines**
**URL**: [https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines)
**Description**: Microsoft's official naming conventions for .NET libraries.
**Use For**:
- .NET naming standards
- PascalCase/camelCase usage
- Namespace organization
- Framework design guidelines
#### C/C++ - Doxygen
**URL**: [https://www.doxygen.nl/](https://www.doxygen.nl/)
**Description**: Documentation generator supporting multiple languages including C++, C#, PHP, Java, and Python.
**Use For**:
- C/C++ API documentation
- Multi-language documentation
- Diagram generation
- Cross-platform documentation
**Manual**: [https://www.doxygen.nl/manual/](https://www.doxygen.nl/manual/)
#### Python - Sphinx
**URL**: [https://www.sphinx-doc.org/](https://www.sphinx-doc.org/)
**Description**: Documentation generator for Python with reStructuredText support.
**Use For**:
- Python API documentation
- Python package documentation
- Technical documentation
- ReadTheDocs integration
### SAP-Specific Resources
#### SAP API Business Hub
**URL**: [https://api.sap.com/](https://api.sap.com/)
**Description**: Central repository for SAP's REST and OData API references. Provides interactive API exploration, testing, and documentation.
**Use For**:
- Publishing REST/OData APIs
- Discovering SAP APIs
- Testing API endpoints
- Downloading API specifications
**Login Required**: SAP account needed for full access
#### SAP Help Portal
**URL**: [https://help.sap.com/](https://help.sap.com/)
**Description**: Comprehensive SAP product documentation and help resources.
**Use For**:
- Product documentation
- Technical guides
- Configuration guides
- Release notes
#### SAP Developer Center
**URL**: [https://developers.sap.com/](https://developers.sap.com/)
**Description**: Resources for SAP developers including tutorials, code samples, and developer guides.
**Use For**:
- Getting started tutorials
- Code samples
- Developer community
- Learning paths
**Tutorial Navigator**: [https://developers.sap.com/tutorial-navigator.html](https://developers.sap.com/tutorial-navigator.html)
#### SAP Community
**URL**: [https://community.sap.com/](https://community.sap.com/)
**Description**: SAP's community platform for asking questions, sharing knowledge, and connecting with other developers.
**Use For**:
- Community support
- Best practices
- Code sharing
- Networking
#### SAP Business Accelerator Hub (formerly API Business Hub)
**URL**: [https://api.sap.com/](https://api.sap.com/)
**Description**: Updated name for SAP API Business Hub. Provides APIs, events, and integrations.
**Use For**:
- API discovery and exploration
- Integration content
- Pre-built integrations
- API package management
---
## SAP-Specific Resources
### SAP API Style Guide Repository
**URL**: [https://github.com/SAP-docs/api-style-guide](https://github.com/SAP-docs/api-style-guide)
**Description**: Official SAP API Style Guide source repository containing all documentation standards.
**Contents**:
- API naming guidelines
- REST/OData documentation standards
- Java/JavaScript/.NET documentation
- Manual template guidelines
- Deprecation policy
- Quality processes
**Last Updated**: 2021.01
**Clone Command**:
```bash
git clone [https://github.com/SAP-docs/api-style-guide.git](https://github.com/SAP-docs/api-style-guide.git)
```
### SAP BTP (Business Technology Platform)
**Cockpit**: [https://cockpit.sap.com/](https://cockpit.sap.com/)
**Documentation**: [https://help.sap.com/docs/BTP](https://help.sap.com/docs/BTP)
**API Documentation**: Available through SAP API Business Hub
### SAP Integration Suite
**URL**: [https://help.sap.com/docs/INTEGRATION_SUITE](https://help.sap.com/docs/INTEGRATION_SUITE)
**Includes**:
- API Management
- Integration Advisor
- Open Connectors
- API Designer (bundled with Integration Suite)
**Use For**:
- Creating and managing APIs
- API design and development
- Integration patterns
- API lifecycle management
### SAP NetWeaver
**JavaScript API Example**: Available through SAP NetWeaver documentation
**URL**: [https://help.sap.com/docs/SAP_NETWEAVER](https://help.sap.com/docs/SAP_NETWEAVER)
**Use For**:
- JavaScript API patterns
- NetWeaver-specific documentation
- Portal development
---
## Quick Reference
### By Language/Technology
| Language/Tech | Standard | Tool | Documentation |
|---------------|----------|------|---------------|
| **Java** | Javadoc | javadoc | [Oracle Javadoc](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html) |
| **JavaScript** | JSDoc 3 | jsdoc | [JSDoc](https://jsdoc.app/) |
| **.NET (C#)** | XML Comments | DocFX, Sandcastle | [Microsoft XML Docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/) |
| **C/C++** | Doxygen | doxygen | [Doxygen Manual](https://www.doxygen.nl/manual/) |
| **Python** | reStructuredText | Sphinx | [Sphinx](https://www.sphinx-doc.org/) |
| **REST** | OpenAPI | Swagger, Redoc | [OpenAPI Spec](https://spec.openapis.org/oas/latest.html) |
| **OData** | OData 4.01 | Various | [OData.org](https://www.odata.org/) |
### By Documentation Type
| Documentation Type | Primary Resource | Secondary Resource |
|-------------------|------------------|-------------------|
| **REST API Reference** | OpenAPI Spec | SAP API Business Hub |
| **OData API Reference** | OData Spec | SAP API Business Hub |
| **Java API Reference** | Javadoc Guide | SAP Naming Guidelines |
| **JavaScript API Reference** | JSDoc Guide | SAP Naming Guidelines |
| **.NET API Reference** | Microsoft XML Docs | SAP Naming Guidelines |
| **Developer Guides** | SAP Developer Center | SAP Help Portal |
| **Tutorials** | SAP Tutorial Navigator | SAP Community |
| **Code Samples** | SAP API Business Hub | GitHub |
### By Task
| Task | Resource | URL |
|------|----------|-----|
| **Find SAP APIs** | SAP API Business Hub | [https://api.sap.com/](https://api.sap.com/) |
| **Learn SAP Development** | SAP Developer Center | [https://developers.sap.com/](https://developers.sap.com/) |
| **Read Product Docs** | SAP Help Portal | [https://help.sap.com/](https://help.sap.com/) |
| **Ask Questions** | SAP Community | [https://community.sap.com/](https://community.sap.com/) |
| **Design REST APIs** | OpenAPI Spec | [https://spec.openapis.org/](https://spec.openapis.org/) |
| **Design OData APIs** | OData Spec | [https://www.odata.org/](https://www.odata.org/) |
| **Write Java Docs** | Javadoc Guide | [https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html) |
| **Write JS Docs** | JSDoc Guide | [https://jsdoc.app/](https://jsdoc.app/) |
| **Write .NET Docs** | Microsoft Docs | [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/) |
| **Generate C++ Docs** | Doxygen | [https://www.doxygen.nl/](https://www.doxygen.nl/) |
---
## Version Information
### API Standard Versions
| Standard | Current Version | Previous Versions | Status |
|----------|----------------|-------------------|--------|
| **OpenAPI** | 3.0.3 | 2.0 (Swagger), 3.1.0 | Active |
| **OData** | 4.01 | 4.0, 3.0, 2.0 | Active |
| **Javadoc** | Java 17 | Java 8, 11 | Active |
| **JSDoc** | 3.x | 2.x | Active |
| **.NET XML** | .NET 6+ | .NET Framework, .NET Core | Active |
| **Doxygen** | 1.9+ | 1.8.x | Active |
### SAP API Style Guide Versions
| Version | Date | Key Changes |
|---------|------|-------------|
| **2021.01** | January 2021 | API Designer clarification, expanded description guidelines |
| **Initial** | Earlier | Base standards established |
---
## Related SAP Documentation
### Official SAP Standards Documents
1. **SAP API Style Guide** - This complete skill reference
2. **SAP Naming Conventions** - naming-conventions.md
3. **SAP Quality Processes** - quality-processes.md
4. **SAP Deprecation Policy** - deprecation-policy.md
5. **SAP Developer Guides** - developer-guides.md
### SAP Cloud Documentation
- **SAP BTP**: [https://help.sap.com/docs/BTP](https://help.sap.com/docs/BTP)
- **SAP Cloud Foundry**: [https://help.sap.com/docs/BTP/65de2977205c403bbc107264b8eccf4b/](https://help.sap.com/docs/BTP/65de2977205c403bbc107264b8eccf4b/)
- **SAP Kyma**: [https://help.sap.com/docs/BTP/65de2977205c403bbc107264b8eccf4b/](https://help.sap.com/docs/BTP/65de2977205c403bbc107264b8eccf4b/)
### SAP Development Tools
- **SAP Business Application Studio**: [https://help.sap.com/docs/BAS](https://help.sap.com/docs/BAS)
- **SAP Web IDE**: (Deprecated - migrating to Business Application Studio)
- **SAP HANA Cloud**: [https://help.sap.com/docs/HANA_CLOUD](https://help.sap.com/docs/HANA_CLOUD)
---
**Document Version**: 1.0.0
**Last Updated**: 2025-11-21
**Maintainer**: SAP Skills Team | [https://github.com/secondsky/sap-skills](https://github.com/secondsky/sap-skills)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,681 @@
# OData Operation Template
## How to Use This Template
**Purpose**: Document individual OData operations (CRUD, functions, actions) with complete request/response details.
**When to Use**:
- Creating detailed documentation for a specific OData operation
- Documenting CRUD operations with full request/response examples
- Documenting custom functions and actions
- Detailed operation documentation linked from Resource template
**Instructions**:
1. Replace all [bracketed text] with your actual operation information
2. Include complete, working HTTP request examples
3. Show real response examples with actual data and status codes
4. Document all possible status codes for this specific operation
5. Include both success and error response examples
6. Test the operation and verify all examples work
7. Remove optional sections if not applicable
**Cross-Reference**: Use with [OData Resource Template](#odata-resource-template) for resource context and [OData Service Overview Template](#odata-service-overview-template) for service-level info.
**Template Structure**:
- Title & Introduction
- Operation Details (type, HTTP method, permission)
- Request (headers, parameters, body, examples)
- Response (headers, status codes, body, examples)
---
## [Operation Name] ([HTTP Method])
[Provide comprehensive description of what this operation does. Include:
- What action is performed
- What is returned (if applicable)
- When to use this operation
- Important behaviors or side effects]
**Example**:
"Creates a new employee record in the system with provided information.
Automatically assigns unique employee ID and initializes default values
(status: ACTIVE, creation timestamp). Triggers HR workflow notifications."
---
## Usage
[Explain when and why to use this operation, including:
- Primary use cases and scenarios
- When to use alternative operations
- Important prerequisites or constraints
- Any special behaviors or workflows]
Use this operation to [describe scenario].
Key points:
- [Important characteristic or constraint]
- [Related operation if applicable]
- [Performance consideration if relevant]
- [Workflow impact or side effect if relevant]
**Example**:
"Use this operation when adding a new employee to the system. Required fields
include first name, last name, email, and department. Optional fields like
hire date and salary can be provided.
Key points:
- Automatically generates unique EmployeeID
- Email must be unique across system
- Returns created employee in response body (if Prefer header included)
- Triggers HR workflow notifications to department manager
- Related operations: PATCH for updates, GET for retrieval"
---
## Request
### Operation Details
**URI**: [HTTP Method] [Path]
**Example**: `POST /Employees`, `GET /Employees('E12345')`, `PATCH /Employees('E12345')`
**Operation Type**: [CRUD/Function/Action]
| Aspect | Value |
|---|---|
| HTTP Method | [GET/POST/PUT/PATCH/DELETE] |
| Operation Type | [CRUD (standard)/Function (returns data)/Action (performs action)] |
| Resource | [Resource name] |
| Full URI Pattern | [Complete URI pattern with placeholders] |
**Example**:
```
| Aspect | Value |
|---|---|
| HTTP Method | POST |
| Operation Type | CRUD (Create) |
| Resource | Employees |
| Full URI Pattern | POST /Employees |
```
### Required Permission
**Permission**: [Required role or permission level]
[Explanation of what this permission allows and why it's required]
**Example**:
"Permission: ROLE_HR_MANAGER or ROLE_ADMIN
Only users with ROLE_HR_MANAGER or higher role can create employees.
Lower roles like ROLE_HR_USER cannot call this operation."
### Request Headers
| Header Name | Required | Possible Values | Description |
|---|---|---|---|
| [Header] | [Yes/No] | [Values] | [Description with format/examples] |
**Example**:
```
| Header Name | Required | Possible Values | Description |
|---|---|---|---|
| Authorization | Yes | Bearer {token} | OAuth2 authentication token. Format: Bearer {token}. Required for all operations. |
| Content-Type | Yes (POST/PUT/PATCH) | application/json | Media type of request body. Required for operations with request body. Value: application/json |
| Accept | No | application/json | Preferred response format. Default: application/json. Optional: specify other formats if supported. |
| Prefer | No | return=representation, return=minimal | OData preference. return=representation: include created/updated entity in response. return=minimal: response without body (faster). |
| If-Match | No | {ETag} | ETag for optimistic concurrency control. Format: quoted string (e.g., "abc123"). Required for safe concurrent updates on PUT/PATCH. |
| X-Request-ID | No | UUID | Optional request tracking ID. Format: any valid UUID. Example: 123e4567-e89b-12d3-a456-426614174000 |
```
### Request Parameters
[Document all parameters passed to the operation, organized by location.]
#### Path Parameters
[If operation uses path parameters in URI]
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| [Name] | Required/Optional | [Type] | [Description with constraints, pattern, valid values] | Path |
**Example**:
```
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| EmployeeID | Required | String | Employee unique identifier. Pattern: E[0-9]{5}. Example: "E12345" | Path |
```
#### Query Parameters
[If operation uses query parameters]
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| $filter | Optional | String | OData filter expression for query. Example: FirstName eq 'John'. Used only in GET collection operations. | Query |
| $orderby | Optional | String | Sort order. Example: HireDate desc, LastName asc. Used in GET collection operations. | Query |
| $top | Optional | Integer | Maximum records to return (1-1000). Default: 50. Used for pagination. | Query |
| $skip | Optional | Integer | Records to skip for pagination. Default: 0. Used with $top. | Query |
| $select | Optional | String | Properties to include in response. Example: FirstName,LastName,Email. Reduces payload size. | Query |
| $expand | Optional | String | Navigate relationships and include related data. Example: Department,Manager. Limited to 3 levels deep. | Query |
**Detailed Example for POST**:
```
[No query parameters for POST operations - all data in request body]
```
**Detailed Example for GET with Collection**:
```
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| $filter | Optional | String | Filter expression. Example: $filter=Status eq 'ACTIVE' and Salary gt 100000 | Query |
| $orderby | Optional | String | Sort fields. Example: $orderby=HireDate desc,LastName asc | Query |
| $top | Optional | Integer | Max results (1-1000, default: 50). Example: $top=100 | Query |
| $skip | Optional | Integer | Records to skip for pagination. Example: $skip=200 | Query |
| $select | Optional | String | Properties to include. Example: $select=FirstName,LastName,Email | Query |
| $expand | Optional | String | Include related data. Example: $expand=Department,Manager | Query |
| $count | Optional | Boolean | Include total count. Returns entities with @odata.count. Value: true. Example: ?$count=true. Note: Path /Employees/$count returns only integer count. | Query |
```
#### Request Body
[For POST/PUT/PATCH operations with request body]
**Format**: [JSON structure with all properties]
**Required Fields**: [List of required fields]
**Optional Fields**: [List of optional fields]
| Property Name | Requirement | Data Type | Description | Constraints |
|---|---|---|---|---|
| [Property] | Required/Optional | [Type] | [Description] | [Min/max, format, valid values] |
**Example**:
```
Request body structure:
{
"FirstName": "string",
"LastName": "string",
"Email": "string",
"Department": "string",
"HireDate": "date",
"Salary": "decimal"
}
Required Fields: FirstName, LastName, Email, Department
Optional Fields: HireDate, Salary
| Property Name | Requirement | Data Type | Description | Constraints |
|---|---|---|---|---|
| FirstName | Required | String | Employee's first name | 1-50 characters, alphanumeric + spaces |
| LastName | Required | String | Employee's last name | 1-50 characters, alphanumeric + spaces |
| Email | Required | String | Corporate email address | Must be unique, valid email format (RFC 5322) |
| Department | Required | String | Department code | Valid: "SALES", "ENGINEERING", "FINANCE", "HR", "OPERATIONS" |
| HireDate | Optional | Date | Hire date in YYYY-MM-DD format | Cannot be future date, ISO 8601 format |
| Salary | Optional | Decimal | Annual salary in USD | Minimum: 20000, maximum: 10000000, 2 decimal places |
```
### Request Example
[Provide complete, working HTTP request with all headers and body.]
**Template**:
```http
[HTTP METHOD] [Path]?[Query Parameters] HTTP/1.1
Host: [Host]
Authorization: Bearer [token]
Content-Type: application/json
[Additional Headers]
[Request body if applicable]
```
#### Example - GET Collection with Filtering
```http
GET /Employees?$filter=Status eq 'ACTIVE' and Department eq 'ENGINEERING'&$orderby=LastName asc&$top=50&$skip=0 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
```
#### Example - GET Single Resource
```http
GET /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
```
#### Example - POST (Create)
```http
POST /Employees HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Prefer: return=representation
```
#### Example - PATCH (Update)
```http
PATCH /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
If-Match: "abc123def456"
```
#### Example - PUT (Replace)
```http
PUT /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
```
#### Example - DELETE
```http
DELETE /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```
---
## Response
### Response Headers
| Header Name | Description | Possible Values |
|---|---|---|
| [Header] | [What this header contains] | [Example values] |
**Example**:
```
| Header Name | Description | Possible Values |
|---|---|---|
| Content-Type | Response body media type | application/json |
| Location | URL of created/modified resource | [https://api.example.com/odata/v4/Employees('E12346](https://api.example.com/odata/v4/Employees('E12346)') |
| ETag | Entity tag for caching and concurrency control | "abc123def456" |
| OData-Version | OData protocol version used | 4.0 |
| Preference-Applied | Which Prefer preference was applied | return=representation, return=minimal |
```
### Status Codes
| Status Code | Description | Conditions | Response Body |
|---|---|---|---|
| [Code] | [What status means] | [When this occurs] | [Type of response body] |
**Example for GET (200 OK)**:
```
| Status Code | Description | Conditions | Response Body |
|---|---|---|---|
| 200 OK | Request successful | Entity/collection retrieved | Entity or collection data |
| 401 Unauthorized | Authentication required | Missing/invalid token | Error object |
| 403 Forbidden | Insufficient permissions | User lacks required role | Error object |
| 404 Not Found | Resource doesn't exist | Invalid ID/key | Error object |
| 500 Internal Server Error | Server error | Unhandled exception | Error object |
```
**Example for POST (201 Created)**:
```
| Status Code | Description | Conditions | Response Body |
|---|---|---|---|
| 201 Created | Resource created successfully | Valid request, auto-generated ID | Created entity (if Prefer: return=representation) |
| 400 Bad Request | Validation error | Invalid data, missing required field | Error object with details |
| 401 Unauthorized | Authentication required | Missing/invalid token | Error object |
| 403 Forbidden | Insufficient permissions | User lacks ROLE_HR_MANAGER | Error object |
| 409 Conflict | Duplicate/constraint violation | Email already exists | Error object with details |
| 500 Internal Server Error | Server error | Database error | Error object |
```
**Example for PATCH (204 No Content or 200 OK)**:
```
| Status Code | Description | Conditions | Response Body |
|---|---|---|---|
| 204 No Content | Update successful | Default response without Prefer header | Empty body |
| 200 OK | Update successful | Prefer: return=representation | Updated entity data |
| 400 Bad Request | Validation error | Invalid field values | Error object |
| 401 Unauthorized | Authentication required | Missing/invalid token | Error object |
| 403 Forbidden | Insufficient permissions | User lacks required role | Error object |
| 404 Not Found | Resource doesn't exist | Invalid ID | Error object |
| 412 Precondition Failed | Optimistic concurrency failure | If-Match ETag mismatch | Error object |
| 500 Internal Server Error | Server error | Database error | Error object |
```
### Response Body (Successful)
[Document the successful response body structure, including all properties.]
```json
{
"[property]": "[value or type]",
"[property]": "[value or type]"
}
```
**Example for GET Single (200 OK)**:
```json
{
"EmployeeID": "E12345",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com",
"Department": "ENGINEERING",
"HireDate": "2020-06-01",
"Salary": 120000.00,
"Status": "ACTIVE",
"CreatedAt": "2020-06-01T09:00:00Z",
"LastModified": "2024-01-15T14:30:00Z"
}
```
**Example for GET Collection (200 OK)**:
```json
{
"value": [
{
"EmployeeID": "E12345",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com",
"Status": "ACTIVE"
},
{
"EmployeeID": "E12346",
"FirstName": "Jane",
"LastName": "Smith",
"Email": "jane.smith@company.com",
"Status": "ACTIVE"
}
]
}
```
**Example for POST (201 Created)**:
```json
{
"EmployeeID": "E12346",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com",
"Department": "ENGINEERING",
"HireDate": "2024-01-15",
"Salary": 95000.00,
"Status": "ACTIVE",
"CreatedAt": "2024-01-15T10:30:00Z",
"LastModified": "2024-01-15T10:30:00Z"
}
```
---
## Complete Response Examples
### Success Response (200 OK - GET)
```http
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "abc123def456"
OData-Version: 4.0
```
### Success Response (201 Created - POST)
```http
HTTP/1.1 201 Created
Content-Type: application/json
Location: [https://api.example.com/odata/v4/Employees('E12346](https://api.example.com/odata/v4/Employees('E12346)')
ETag: "def789ghi123"
OData-Version: 4.0
```
### Success Response (204 No Content - PATCH)
```http
HTTP/1.1 204 No Content
```
### Success Response (Collection - GET with $top/$skip)
```http
HTTP/1.1 200 OK
Content-Type: application/json
OData-Version: 4.0
```
---
## Error Response Examples
### Error Response (400 Bad Request)
```http
HTTP/1.1 400 Bad Request
Content-Type: application/json
```
### Error Response (401 Unauthorized)
```http
HTTP/1.1 401 Unauthorized
Content-Type: application/json
```
### Error Response (403 Forbidden)
```http
HTTP/1.1 403 Forbidden
Content-Type: application/json
```
### Error Response (404 Not Found)
```http
HTTP/1.1 404 Not Found
Content-Type: application/json
```
### Error Response (409 Conflict - Duplicate)
```http
HTTP/1.1 409 Conflict
Content-Type: application/json
```
### Error Response (500 Internal Server Error)
```http
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
```
---
## Special Cases / Additional Notes
[Document any special behaviors, edge cases, or implementation notes]
**Example**:
- Soft delete: Employee records are marked with Status='TERMINATED', not physically deleted
- Automatic fields: EmployeeID, CreatedAt, and LastModified are auto-generated
- Optimistic concurrency: Use If-Match header with ETag to prevent lost updates
- Batch operations: This operation can be included in a $batch request
- Rate limiting: This operation counts as 1 request toward rate limit
---
## Related Operations
- [Resource Overview](#odata-resource-[name])
- [Service Overview](#odata-service-[name])
- [Related Operation 1](#odata-operation-[name])
- [Related Operation 2](#odata-operation-[name])
---
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50
{
"field": "Email",
"issue": "Email already exists in system",
"value": "john.doe@company.com",
"existingEmployeeId": "E10001"
},
{
"field": "Salary",
"issue": "Minimum salary must be at least 20000",
"value": "15000"
}
]
}
}
```
### Error Response (401 Unauthorized)
```http
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"code": "AUTHENTICATION_FAILED",
"message": "Authentication token missing, invalid, or expired",
"details": {
"reason": "Bearer token not provided in Authorization header"
}
}
}
```
### Error Response (403 Forbidden)
```http
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": {
"code": "INSUFFICIENT_PERMISSION",
"message": "Insufficient permissions for this operation",
"details": {
"requiredRole": "ROLE_HR_MANAGER",
"userRole": "ROLE_HR_USER",
"operation": "Create Employee"
}
}
}
```
### Error Response (404 Not Found)
```http
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"code": "NOT_FOUND",
"message": "Requested resource not found",
"details": {
"resourceType": "Employee",
"providedId": "E99999",
"suggestion": "Verify the employee ID exists and hasn't been deleted"
}
}
}
```
### Error Response (409 Conflict - Duplicate)
```http
HTTP/1.1 409 Conflict
Content-Type: application/json
{
"error": {
"code": "DUPLICATE_EMAIL",
"message": "Employee with provided email already exists",
"details": {
"email": "john.doe@company.com",
"existingEmployeeId": "E10001",
"existingEmployeeName": "John Doe"
}
}
}
```
### Error Response (500 Internal Server Error)
```http
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "Server encountered an unexpected error",
"details": {
"traceId": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2024-01-15T14:30:00Z",
"suggestion": "Contact support with provided trace ID"
}
}
}
```
---
## Special Cases / Additional Notes
[Document any special behaviors, edge cases, or implementation notes]
**Example**:
- Soft delete: Employee records are marked with Status='TERMINATED', not physically deleted
- Automatic fields: EmployeeID, CreatedAt, and LastModified are auto-generated
- Optimistic concurrency: Use If-Match header with ETag to prevent lost updates
- Batch operations: This operation can be included in a $batch request
- Rate limiting: This operation counts as 1 request toward rate limit
---
## Related Operations
- [Resource Overview](#odata-resource-[name])
- [Service Overview](#odata-service-[name])
- [Related Operation 1](#odata-operation-[name])
- [Related Operation 2](#odata-operation-[name])
---
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50

View File

@@ -0,0 +1,557 @@
# OData Resource Template
## How to Use This Template
**Purpose**: Document individual OData resources (entity sets) within a service with all available operations.
**When to Use**:
- Creating detailed documentation for a specific OData entity set/resource
- Documenting all CRUD operations on a resource
- Listing navigation properties and custom functions/actions
- Linking from Service Overview to specific resource documentation
**Instructions**:
1. Replace all [bracketed text] with your actual resource information
2. Verify all operations against service metadata
3. Document navigation properties with cardinality (1:1, 1:N)
4. Include permission requirements for each operation type
5. List custom functions and actions with brief descriptions
6. Remove optional sections if not applicable
**Cross-Reference**: Use with [OData Service Overview Template](#odata-service-overview-template) for service context and [OData Operation Template](#odata-operation-template) for detailed operation docs.
**Template Structure**:
- Title & Introduction
- Resource Information (path, key, permissions)
- Operations (CRUD, navigation, custom)
- Common Headers
- Status and Error Codes
- Examples
---
## [Resource Name] Resource
[Provide clear description of what this resource represents and contains. Include:
- What business entity or data domain it covers
- Primary use cases
- Relationship to other resources
- Scope or limitations]
**Example**:
"Collection of all employees in the system. Provides access to employee master
data including personal information, organizational assignments, employment
status, and related compensation information. Navigation properties allow
access to related departments, managers, and compensation details."
### Additional Context
[Any important information about this resource]
This resource represents [explain domain/purpose]. Use for [primary use cases].
Navigation properties allow [explain relationships].
---
## Resource Information
### Resource Path
**Path**: `[Relative path to entity set, e.g., /Employees]`
[Explanation of resource path]
### Absolute URI
**Absolute URI**: `[Root URI]/[Resource Path]`
**Example**: `[https://api.example.com/odata/v4/Employees`](https://api.example.com/odata/v4/Employees`)
### Key Property
**Key Property**: [Property name that uniquely identifies each resource]
[Description of key property and format/pattern]
**Example**:
```
Key Property: EmployeeID
Type: String
Format: E followed by 5 digits
Pattern: E[0-9]{5}
Example: E12345
```
### Individual Resource Addressing
[How to address/access a single resource by key]
**URI Pattern**: `[Resource Path]('{[Key Value]}')`
**Examples**:
- `/Employees('E12345')` - Address by string key
- `/Employees(EmployeeID='E12345')` - Explicit property name
- `[https://api.example.com/odata/v4/Employees('E12345](https://api.example.com/odata/v4/Employees('E12345)')` - Absolute URI
### Required Permissions
[Document permissions for different operation types on this resource]
| Operation Type | Required Permission | Description |
|---|---|---|
| Read/Query | [Role] | [What permission is needed and what it allows] |
| Create (POST) | [Role] | [Permission required] |
| Update (PUT/PATCH) | [Role] | [Permission required] |
| Delete | [Role] | [Permission required] |
**Example**:
```
| Operation Type | Required Permission | Description |
|---|---|---|
| Read/Query | ROLE_HR_USER | Read-only access to all employee data |
| Create (POST) | ROLE_HR_MANAGER | Create new employee records |
| Update (PUT/PATCH) | ROLE_HR_MANAGER | Modify existing employee data |
| Delete | ROLE_ADMIN | Delete employee records (limited to admins) |
```
### Resource Properties
[Complete list of all properties available on this resource]
| Property Name | Data Type | Description | Example | Notes |
|---|---|---|---|---|
| [Property] | [Type] | [Description] | [Example value] | [Nullable, constraints, etc.] |
**Example**:
```
| Property Name | Data Type | Description | Example | Notes |
|---|---|---|---|---|
| EmployeeID | String | Unique employee identifier | E12345 | Key property, not null |
| FirstName | String | Employee's first name | John | 1-50 characters, required |
| LastName | String | Employee's last name | Doe | 1-50 characters, required |
| Email | String | Corporate email address | john.doe@company.com | Must be unique, required |
| HireDate | Date | Employment start date | 2024-01-15 | ISO 8601 format, optional |
| Status | String | Employment status | ACTIVE | Values: ACTIVE, INACTIVE, ON_LEAVE, TERMINATED |
| Salary | Decimal | Annual salary | 95000.00 | Nullable, 2 decimal places |
| CreatedAt | DateTime | Record creation timestamp | 2024-01-15T10:30:00Z | UTC, auto-set |
| LastModified | DateTime | Last modification timestamp | 2024-01-15T14:30:00Z | UTC, auto-updated |
```
---
## Operations
### CRUD Operations
Standard Create, Read, Update, Delete operations available on this resource:
| HTTP Method | Operation | URI | Description |
|---|---|---|---|
| GET | [Read Collection](#operation-read-collection) | `[Resource]` | Retrieve all resources |
| GET | [Read Single](#operation-read-single) | `[Resource]('{Key}')` | Retrieve specific resource |
| POST | [Create](#operation-create) | `[Resource]` | Create new resource |
| PUT | [Replace](#operation-replace) | `[Resource]('{Key}')` | Replace entire resource |
| PATCH | [Update](#operation-update) | `[Resource]('{Key}')` | Partial update resource |
| DELETE | [Delete](#operation-delete) | `[Resource]('{Key}')` | Delete resource |
**Example**:
```
| HTTP Method | Operation | URI | Description |
|---|---|---|---|
| GET | [Query all employees](#operation-read-collection) | `/Employees` | Retrieve all employees with optional filtering and paging |
| GET | [Get single employee](#operation-read-single) | `/Employees('{EmployeeID}')` | Retrieve specific employee by ID |
| POST | [Create employee](#operation-create) | `/Employees` | Create new employee record |
| PUT | [Replace employee](#operation-replace) | `/Employees('{EmployeeID}')` | Replace entire employee record |
| PATCH | [Update employee](#operation-update) | `/Employees('{EmployeeID}')` | Partial update of employee fields |
| DELETE | [Delete employee](#operation-delete) | `/Employees('{EmployeeID}')` | Delete/deactivate employee |
```
### Navigation Properties
[If resource has relationships to other entities, document navigation properties]
**Navigation Properties**:
| Navigation Name | Target Entity | Cardinality | Description |
|---|---|---|---|
| [Property] | [Entity] | [1:1 / 1:N] | [Description of relationship] |
**Example**:
```
| Navigation Name | Target Entity | Cardinality | Description |
|---|---|---|---|
| Department | Department | 1:1 | Navigate to employee's department |
| Manager | Employee | 1:1 | Navigate to employee's manager (another employee) |
| DirectReports | Employee | 1:N | Navigate to employees reporting to this employee |
| Compensation | Compensation | 1:1 | Navigate to compensation details |
```
**How to Use Navigation Properties**:
Using `$expand` to include related data:
```
GET /Employees?$expand=Department HTTP/1.1
Returns employee(s) with embedded Department entity data.
```
Using `$expand` with `$select` to limit properties:
```
GET /Employees?$expand=Department($select=DepartmentID,Name) HTTP/1.1
Returns employee(s) with only specific Department properties included.
```
Multi-level expansion:
```
GET /Employees?$expand=Department,Manager($expand=Department) HTTP/1.1
Includes Department for the employee and Department for the manager.
Maximum expansion depth: [specify limit, e.g., 3 levels]
```
### Custom Functions and Actions
[If resource supports custom functions or actions, document them]
| Operation Type | Name | URI | Description |
|---|---|---|---|
| [Function/Action] | [Name] | [URI Pattern] | [Description] |
**Example**:
```
| Operation Type | Name | URI | Description |
|---|---|---|---|
| Function | GetManager | `/Employees('{EmployeeID}')/GetManager()` | Get the direct manager of an employee |
| Function | GetDirectReports | `/Employees('{EmployeeID}')/GetDirectReports()` | Get all direct reports of an employee |
| Action | Promote | `/Employees('{EmployeeID}')/Promote` | Promote employee to next level (requires payload with details) |
| Action | Deactivate | `/Employees('{EmployeeID}')/Deactivate` | Mark employee as inactive |
```
**Detailed Function/Action Information**:
For each custom operation, provide:
- Purpose and use case
- Request parameters (if any)
- Return type
- Permission requirements
- Example request/response
---
## Common Headers
### Request Headers
| Header Name | Required | Possible Values | Description |
|---|---|---|---|
| [Header] | [Yes/No] | [Values] | [Description with format/examples] |
**Example**:
```
| Header Name | Required | Possible Values | Description |
|---|---|---|---|
| Authorization | Yes | Bearer {token} | OAuth2 authentication token in format: Authorization: Bearer {token} |
| Content-Type | Yes (POST/PUT/PATCH) | application/json | Media type of request body for create/update operations |
| Accept | No | application/json | Preferred response format. Default: application/json. Value: application/json |
| Prefer | No | return=representation, return=minimal | OData preference. return=representation: include created/updated resource. return=minimal: response without body. |
| If-Match | No | {ETag} | ETag value for optimistic concurrency control on PUT/PATCH. Example: "abc123def456". Prevents lost-update problem. |
| X-Request-ID | No | UUID | Request tracking ID for logging and debugging. Any valid UUID format. Optional but recommended. |
```
### Response Headers
| Header Name | Description | Example Value |
|---|---|---|
| [Header] | [What this header contains] | [Example] |
**Example**:
```
| Header Name | Description | Example Value |
|---|---|---|
| Content-Type | Response body media type | application/json |
| ETag | Entity tag for caching and optimistic concurrency | "abc123def456" |
| Location | URL of newly created resource (201 responses) | [https://api.example.com/odata/v4/Employees('E12346](https://api.example.com/odata/v4/Employees('E12346)') |
| OData-Version | OData protocol version | 4.0 |
| Preference-Applied | Which Prefer header preference was applied | return=representation |
```
---
## Status and Error Codes
### Common Status Codes
| Status Code | Description | Typical Scenarios |
|---|---|---|
| [Code] | [Description] | [When this occurs] |
**Example**:
```
Success Codes:
| Status Code | Description | Typical Scenarios |
|---|---|---|
| 200 OK | Request successful. Response body contains requested data. | GET operations, POST with Prefer: return=representation |
| 201 Created | Resource successfully created. Location header contains new resource URL. | POST operations creating new entity |
| 204 No Content | Request successful. No response body returned. | DELETE operations, PUT/PATCH with Prefer: return=minimal |
Error Codes:
| Status Code | Description | Typical Scenarios |
|---|---|---|
| 400 Bad Request | Invalid request format, syntax, or OData query error. Response includes error details. | Malformed filter syntax, missing required fields, invalid data types |
| 401 Unauthorized | Authentication token missing, invalid, or expired. | Missing Authorization header, invalid token, expired token |
| 403 Forbidden | Authenticated but insufficient permissions for operation. | User lacks required role, permission denied for operation |
| 404 Not Found | Requested resource doesn't exist. | Invalid resource ID/key, deleted resource |
| 409 Conflict | Request conflicts with current state (duplicate, constraint violation). | Duplicate key/email, unique constraint violation, data conflict |
| 500 Internal Server Error | Server encountered unexpected error. | Unhandled server exception, database error |
```
---
## Examples
### Query All Resources
Retrieve all resources with optional filtering, selection, ordering, and pagination:
**Request**:
```http
GET /[ResourceName]?$filter=[filter]&$select=[properties]&$orderby=[property]&$top=[limit]&$skip=[offset] HTTP/1.1
Host: [host]
Authorization: Bearer {token}
Accept: application/json
```
**Example - Get all active employees, sorted by name, limit 20**:
```http
GET /Employees?$filter=Status eq 'ACTIVE'&$select=EmployeeID,FirstName,LastName,Email&$orderby=LastName asc&$top=20&$skip=0 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
```
**Response** (200 OK):
```http
HTTP/1.1 200 OK
Content-Type: application/json
OData-Version: 4.0
{
"value": [
{
"EmployeeID": "E12345",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com"
},
{
"EmployeeID": "E12346",
"FirstName": "Jane",
"LastName": "Smith",
"Email": "jane.smith@company.com"
}
]
}
```
### Query Single Resource
Retrieve a single resource by key:
**Request**:
```http
GET /[ResourceName]('{Key}') HTTP/1.1
Host: [host]
Authorization: Bearer {token}
Accept: application/json
```
**Example**:
```http
GET /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
```
**Response** (200 OK):
```http
HTTP/1.1 200 OK
Content-Type: application/json
ETag: "abc123def456"
{
"EmployeeID": "E12345",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com",
"Department": "ENGINEERING",
"HireDate": "2020-06-01",
"Salary": 120000.00,
"Status": "ACTIVE"
}
```
### Query with Navigation Expansion
Include related entity data:
**Request**:
```http
GET /Employees('E12345')?$expand=Department,Manager($select=FirstName,LastName) HTTP/1.1
Host: api.example.com
Authorization: Bearer {token}
Accept: application/json
```
**Response** (200 OK):
```http
HTTP/1.1 200 OK
Content-Type: application/json
{
"EmployeeID": "E12345",
"FirstName": "John",
"LastName": "Doe",
"Email": "john.doe@company.com",
"Department": {
"DepartmentID": "ENG",
"Name": "Engineering",
"Location": "San Francisco"
},
"Manager": {
"FirstName": "Jane",
"LastName": "Smith"
},
"Status": "ACTIVE"
}
```
### Create Resource
Create a new resource:
**Request**:
```http
POST /[ResourceName] HTTP/1.1
Host: [host]
Authorization: Bearer {token}
Content-Type: application/json
Prefer: return=representation
[Request body with resource properties]
```
**Example**:
```http
POST /Employees HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Prefer: return=representation
{
"FirstName": "Michael",
"LastName": "Johnson",
"Email": "michael.johnson@company.com",
"Department": "SALES",
"HireDate": "2024-01-15",
"Salary": 85000.00
}
```
**Response** (201 Created):
```http
HTTP/1.1 201 Created
Content-Type: application/json
Location: [https://api.example.com/odata/v4/Employees('E12347](https://api.example.com/odata/v4/Employees('E12347)')
{
"EmployeeID": "E12347",
"FirstName": "Michael",
"LastName": "Johnson",
"Email": "michael.johnson@company.com",
"Department": "SALES",
"HireDate": "2024-01-15",
"Salary": 85000.00,
"Status": "ACTIVE",
"CreatedAt": "2024-01-15T10:30:00Z"
}
```
### Update Resource
Partially update a resource using PATCH:
**Request**:
```http
PATCH /[ResourceName]('{Key}') HTTP/1.1
Host: [host]
Authorization: Bearer {token}
Content-Type: application/json
If-Match: "{ETag}"
[Request body with properties to update]
```
**Example - Update salary and department**:
```http
PATCH /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
If-Match: "abc123def456"
{
"Department": "ENGINEERING",
"Salary": 125000.00
}
```
**Response** (204 No Content):
```http
HTTP/1.1 204 No Content
```
### Delete Resource
Delete a resource:
**Request**:
```http
DELETE /[ResourceName]('{Key}') HTTP/1.1
Host: [host]
Authorization: Bearer {token}
```
**Example**:
```http
DELETE /Employees('E12345') HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```
**Response** (204 No Content):
```http
HTTP/1.1 204 No Content
```
---
## Related Documentation
- **Parent Service**: [Service Name](#[service-anchor])
- **Detailed Operations**:
- [Create](#odata-operation-create)
- [Read](#odata-operation-read)
- [Update](#odata-operation-update)
- [Delete](#odata-operation-delete)
- **Related Resources**: [Other Resource Name](#)
---
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50

View File

@@ -0,0 +1,411 @@
# OData Service Overview Template
## How to Use This Template
**Purpose**: Document a complete OData service with metadata, supported features, and resource listing.
**When to Use**:
- Creating documentation for an entire OData v2, v3, or v4 service
- Need to document service-level metadata, features, and entity relationships
- Providing comprehensive service overview before detailed resource documentation
**Instructions**:
1. Replace all [bracketed text] with your actual service information
2. Verify OData version and supported features against actual service metadata
3. Document complete entity data model with relationships
4. Provide accurate metadata URI and service endpoints
5. Test service metadata endpoint and verify all documented features
6. Remove optional sections if not applicable
**Cross-Reference**: Use with [OData Resource Template](#odata-resource-template) for individual resource documentation.
**Template Structure**:
- Title & Introduction
- Overview (version, root URI, permissions)
- OData Feature Support Matrix
- Entity Data Model
- Resources Table
**Token Tip**: Service-level documentation prevents repetition across resource docs, saving ~50% of tokens.
---
## [Service Name] OData Service
[Provide comprehensive description of the OData service. Include:
- Main purpose of the service
- What domains/business areas it covers
- Types of entities available
- Supported operations (CRUD, functions, actions)
- Integration points or workflow support]
**Example**:
"Provides OData v4 API for accessing and managing employee data including
personal information, organizational assignments, compensation details, and
organizational hierarchy. Supports full CRUD operations with complex filtering,
navigation between related entities, and advanced query capabilities."
---
## Overview
### OData Version
**Version**: [2.0 | 3.0 | 4.0]
[Brief explanation of which OData version(s) this service supports. Note any compatibility modes or deprecated versions.]
**Version Information**:
- OData 2.0: Legacy version with limited features
- OData 3.0: Widely supported, intermediate features
- OData 4.0: Latest version with modern features (JSON support, complex types, etc.)
**Example**:
"OData Version: 4.0
The service primarily supports OData v4.0 with modern JSON payload support,
complex filtering, and navigation properties. Backward compatibility for v3.0
available via `/odata/v3` endpoint prefix."
### Root URI
**Root URI**: `[Absolute service path, e.g., [https://api.example.com/odata/v4]`](https://api.example.com/odata/v4]`)
[Explanation of how to construct full URIs from root and include example paths to available resources.]
**Full Service Paths**:
```
Root: [https://api.example.com/odata/v4]
Available resources:
- Employees: [https://api.example.com/odata/v4/Employees]
- Departments: [https://api.example.com/odata/v4/Departments]
- Compensation: [https://api.example.com/odata/v4/Compensation]
```
### Required Permissions
**Permissions**: [List roles and what they allow across the service]
[Explain permission model and any global service-level permissions.]
**Example**:
```
Required Permissions:
- ROLE_HR_USER: Read-only access to all resources
- ROLE_HR_MANAGER: Read and write access to employee and department data
- ROLE_FINANCE: Read-only access to compensation data
- ROLE_ADMIN: Full read/write/delete access to all resources
```
**Permission Model**:
- Global service-level authentication required
- Authentication via OAuth 2.0 Bearer token
- Role-based access control (RBAC) determines allowed operations per resource
- Some resources or operations may have additional permission requirements (see resource documentation)
---
## OData Feature Support
Document which OData features and capabilities the service supports:
| Feature | Supported | Notes |
|---|---|---|
| [OData Feature Name] | [Yes/No/Partial] | [Details, limits, or constraints] |
**Detailed Example**:
| Feature | Supported | Notes |
|---|---|---|
| Filtering ($filter) | Yes | All OData comparison operators supported (eq, ne, lt, le, gt, ge). Logical operators: and, or, not. String functions: contains, startswith, endswith, length, substring. Example: `$filter=FirstName eq 'John' and Status eq 'ACTIVE'` |
| Ordering ($orderby) | Yes | Ascending (asc) and descending (desc) ordering. Single and multiple field sorting. Example: `$orderby=HireDate desc,LastName asc` |
| Paging ($top, $skip) | Yes | Maximum 1000 records per request. Default page size: 50 records. Recommended: use $top with values 10-100. Example: `$top=50&$skip=100` |
| Selection ($select) | Yes | Choose specific properties to include in response. Reduces payload and improves performance. Example: `$select=FirstName,LastName,Email` |
| Expansion ($expand) | Yes | Navigate relationships with limit of 3 levels deep. Expands related entity data inline. Example: `$expand=Department,Manager($select=FirstName,LastName)` |
| Counting ($count) | Yes | Get total count of matching records via `$count` endpoint. Example: `/Employees/$count` |
| Functions | Yes | Custom business function operations available (see resource documentation for specifics). Functions return computed values. |
| Actions | Partial | Limited action support for specific state-changing operations. See resource documentation for available actions. |
| Batch Requests | Yes | Submit multiple operations in single request via `$batch` endpoint. Useful for bulk operations. |
| Batch Change Sets | Yes | Group multiple write operations (POST/PUT/PATCH) in batch change set. Atomic execution. |
| Media Resources | No | File upload/download not currently supported in this version. |
| Null Propagation | Yes | Null values properly handled in filter expressions. |
| Type Casts | Yes | Cast operations in filters (e.g., `cast(Salary, 'Edm.Decimal')`) |
**Common OData Features Explained**:
- **$filter**: Reduces result set to matching records
- **$orderby**: Controls sort order of results
- **$top/$skip**: Implements pagination
- **$select**: Reduces payload by including only needed fields
- **$expand**: Includes related entity data without separate calls
- **$count**: Gets total available records for pagination UI
---
## Entity Data Model
[Document the complete data model including entity types, properties, and relationships.]
### Entity Types
[List and describe each entity type in the service with key properties and relationships.]
**Example**:
**Employee Entity**:
- **Purpose**: Represents individual employee record
- **Key Property**: EmployeeID (string, format: E[0-9]{5})
- **Key Properties**:
- EmployeeID (string): Unique identifier
- FirstName (string): First name
- LastName (string): Last name
- Email (string): Corporate email
- HireDate (date): Employment start date
- Status (string): Employment status (ACTIVE, INACTIVE, ON_LEAVE, TERMINATED)
- Salary (decimal): Annual compensation
- CreatedAt (datetime): Record creation timestamp
- LastModified (datetime): Last modification timestamp
- **Navigation Properties**:
- Department: Single navigation to Department entity
- Manager: Single navigation to managing Employee entity
- Compensation: Single navigation to Compensation entity
- DirectReports (collection): All employees reporting to this employee
**Department Entity**:
- **Purpose**: Represents organizational departments
- **Key Property**: DepartmentID (string)
- **Key Properties**:
- DepartmentID (string): Unique identifier
- Name (string): Department name
- Manager (string): Managing employee ID
- Location (string): Physical location
- CostCenter (string): Cost center code
- **Navigation Properties**:
- Employees (collection): All employees in department
- ParentDepartment: Parent department (for hierarchy)
- SubDepartments (collection): Child departments
**Compensation Entity**:
- **Purpose**: Salary and benefits information
- **Key Property**: CompensationID (string)
- **Key Properties**:
- CompensationID (string): Unique identifier
- EmployeeID (string): Foreign key to Employee
- BaseSalary (decimal): Base annual salary
- Currency (string): Salary currency code (USD, EUR, etc.)
- Benefits (string): Benefits description
- EffectiveDate (date): When compensation became effective
- **Navigation Properties**:
- Employee: Single navigation back to Employee entity
### Entity Relationships
[Document how entities relate to each other.]
**Example**:
```
Employee (1) ---> (1) Department
Employee (1) ---> (1) Employee (Manager)
Employee (1) <--- (N) Employee (DirectReports)
Employee (1) ---> (1) Compensation
Department (1) ---> (N) Employee
Department (1) ---> (1) Department (ParentDepartment)
Department (1) <--- (N) Department (SubDepartments)
```
**Relationship Details**:
- One-to-One (1:1): One employee has one manager
- One-to-Many (1:N): One department has many employees
- Hierarchical: Departments can contain sub-departments up to 10 levels deep
### Service Metadata URI
**Metadata Endpoint**: `[Root URI]/$metadata`
[Explain what metadata contains and how to use it.]
**Example**:
```
Service Metadata URI: [https://api.example.com/odata/v4/$metadata](https://api.example.com/odata/v4/$metadata)
This endpoint returns the complete service definition in CSDL (Common Schema Definition Language) format.
Contains entity type definitions, property types, navigation properties, and available operations.
Useful for:
- Code generation in various programming languages
- Understanding complete service structure
- Discovering available properties and relationships
- Building dynamic OData clients
```
**How to Access Metadata**:
```http
GET [https://api.example.com/odata/v4/$metadata](https://api.example.com/odata/v4/$metadata) HTTP/1.1
Authorization: Bearer {token}
Accept: application/xml
```
### Additional Model Notes
[Document any important data model constraints, patterns, or behaviors.]
**Example**:
```
- All timestamps use UTC format (ISO 8601 standard)
- Employee IDs follow strict pattern: E[0-9]{5} (example: E12345)
- Salary values stored in currency specified in Compensation entity
- Department hierarchies can nest maximum 10 levels deep
- All string properties are case-sensitive in filters
- Datetime properties include millisecond precision
- Decimal properties (salary) use 2 decimal places
- Soft deletes: Terminated employees have Status='TERMINATED' but record remains
```
---
## Resources
[List all entity sets/collections available in the service with descriptions and paths.]
The following resources are available in this OData service:
| Resource Name | Description | Path |
|---|---|---|
| [Entity Set Name] | [Description of resource and primary use] | [Relative path] |
**Detailed Example**:
| Resource Name | Description | Path |
|---|---|---|
| [Employees](#odata-resource-employees) | Collection of all employees in system. Access employee master data including personal information, employment details, and compensation. | `/Employees` |
| [Departments](#odata-resource-departments) | Organization departments and structure. Access department definitions and organizational hierarchy. | `/Departments` |
| [Compensation](#odata-resource-compensation) | Employee compensation and benefits data. Access salary and benefits information linked to employees. | `/Compensation` |
**Resource Guidelines**:
- Resource names link to detailed resource documentation
- Descriptions are concise but informative
- Paths are relative to Root URI
- Order resources alphabetically or by logical grouping
---
## Common Implementation Patterns
[Document common patterns or recommended approaches for using the service.]
### Query with Filtering and Paging
Retrieve active employees with specific fields, sorted and paginated:
```
GET /Employees?$filter=Status eq 'ACTIVE'&$select=EmployeeID,FirstName,LastName,Email
&$orderby=LastName asc&$top=50&$skip=0 HTTP/1.1
```
### Expanding Related Data
Retrieve employees with their department and manager information:
```
GET /Employees?$expand=Department,Manager($select=FirstName,LastName)&$top=10 HTTP/1.1
```
### Complex Filtering
Find employees in Sales department earning over 100,000:
```
GET /Employees?$filter=Department/Name eq 'SALES' and Salary gt 100000&$orderby=Salary desc HTTP/1.1
```
### Batch Requests
Submit multiple operations in single request:
```
POST /$batch HTTP/1.1
[Batch request format with change sets for multiple operations]
```
---
## Authentication and Authorization
[Document authentication mechanism required to access the service.]
**Authentication Type**: OAuth 2.0 Bearer Token
**Token Acquisition**:
1. Obtain OAuth 2.0 token from authentication service
2. Include token in Authorization header: `Authorization: Bearer {token}`
3. Token expires after [time period] - obtain new token when expired
**Required in Every Request**:
```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```
---
## Rate Limiting and Quotas
[Document any service-level rate limits or quotas.]
**Rate Limit**: [requests per time period, e.g., 1000 requests per hour]
**Tracked by**: User/API key
**Rate Limit Headers**:
- X-RateLimit-Limit: Maximum requests in window
- X-RateLimit-Remaining: Requests remaining in current window
- X-RateLimit-Reset: Unix timestamp when window resets
**When Rate Limited**: 429 Too Many Requests response with Retry-After header.
---
## Error Handling
[Document standard error response format for the service.]
**Standard Error Response**:
```json
{
"error": {
"code": "[Error code]",
"message": "[Human-readable message]",
"details": {
"[field]": "[error detail]"
}
}
}
```
**Common OData Error Codes**:
- INVALID_REQUEST: Malformed request
- INVALID_FILTER: Filter syntax error
- RESOURCE_NOT_FOUND: Entity doesn't exist
- PERMISSION_DENIED: Insufficient permissions
- VALIDATION_ERROR: Data validation failure
---
## Additional Information
**Maximum Request Payload**: [size limit, e.g., 10 MB]
**Maximum Response Payload**: [size limit if applicable, e.g., 50 MB]
**Supported Content Types**:
- `application/json` (recommended, OData v4)
- `application/xml` (OData CSDL metadata)
**Related Documentation**:
- [OData Specification](https://www.odata.org/documentation/)
- [OData v4.0 Standard](https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html)
- Service-Specific Documentation: [link]
---
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50

View File

@@ -0,0 +1,477 @@
# REST API Method Template
## How to Use This Template
**Purpose**: Document individual REST API methods/endpoints with complete request and response details.
**When to Use**:
- Creating documentation for a specific REST method (GET, POST, PUT, PATCH, DELETE)
- Detailed endpoint documentation linked from Overview template
- Providing exact parameter requirements and response examples
**Instructions**:
1. Replace all [bracketed text] with your actual content
2. Include complete, working HTTP request examples
3. Show real response examples with actual status codes
4. Document all possible status codes for this specific method
5. Test the endpoint and verify all examples work
6. Remove optional sections if not applicable
**Cross-Reference**: Use with [REST API Overview Template](#rest-api-overview-template) for shared information.
**Template Structure**:
- Title & Introduction
- Usage section
- Request Details (method, permission, headers, parameters)
- Request Example(s)
- Response Details (status codes, body examples)
- Response Examples (success and error cases)
---
## [Action Verb] [Resource Name]
[Provide a clear, concise description of what this method does. Include:
- Primary action performed
- What is retrieved, created, modified, or deleted
- Primary use case
- Key limitations or behaviors]
**Example**:
"Retrieves a complete list of all employees in the system with support for
filtering, sorting, and pagination. Returns employee summary data by default."
### Usage
[Explain when and why to use this method, including:
- Specific scenarios where this method is appropriate
- When to use alternative methods instead
- Important prerequisites or constraints
- Any special behaviors or side effects]
Use this method when [explain primary scenario].
Key points:
- [Important characteristic, constraint, or behavior]
- [Related method or alternative, if applicable]
- [Performance consideration, size limit, or special note]
- [Business logic or workflow impact, if relevant]
**Example**:
"Use this method to retrieve all employee records with optional filtering
and pagination.
Key points:
- Supports filtering by multiple fields using query parameters
- Returns paginated results (default: 20 per page, max: 100 per page)
- Results sorted by employee ID unless otherwise specified via sortBy (e.g., sortBy=employeeId or sortBy=-employeeId for desc)
- Related method: GET /employees/{employeeId} for retrieving specific employee data
- Performance: Large result sets should use pagination to avoid timeout"
---
## Request
### Request Line
```
[HTTP METHOD] [Relative URI Path]
```
**Example**:
```
GET /employees
GET /employees/{employeeId}
POST /employees
PUT /employees/{employeeId}
PATCH /employees/{employeeId}
DELETE /employees/{employeeId}
```
### HTTP Method
**Method**: [GET/POST/PUT/PATCH/DELETE]
[Brief explanation of what this HTTP method does in this context]
**Method Details**:
- GET: Retrieves resource(s) without modifying server state
- POST: Creates new resource with provided data
- PUT: Replaces entire resource with new data
- PATCH: Partially updates resource (merge semantics)
- DELETE: Deletes or deactivates resource
### Permission Requirement
**Permission**: [Required role/permission for this method]
[Explanation of what this permission allows or why it's required]
**Example**:
"Permission: ROLE_HR_MANAGER (read access)
Users with ROLE_HR_MANAGER or higher can call this method.
Lower roles like ROLE_HR_USER cannot access this endpoint."
### Common Request Headers
Refer to [Common Request Headers](#common-request-headers) in the API Overview.
[List any method-specific headers not covered in Overview]
**Additional headers for this method** (if applicable):
- [Header name]: [Description specific to this method]
**Example**:
"Refer to Common Request Headers in overview.
Additional method-specific headers:
- X-Employee-View: Optional header to specify detail level ('summary', 'full', default: 'summary')"
### Path Parameters
[If method has path parameters, include table. Otherwise, state "None".]
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| [Name] | Required/Optional | [Type] | [Detailed description with constraints, pattern, valid values] | Path |
**Example**:
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| employeeId | Required | String | Unique employee identifier. Format: E followed by 5 digits. Pattern: `E[0-9]{5}`. Example: "E12345" | Path |
### Query Parameters
[If method accepts query parameters, include table. Otherwise, state "None".]
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| [Name] | Required/Optional | [Type] | [Description with constraints, valid values, defaults] | Query |
**Example**:
| Parameter Name | Requirement | Data Type | Description | Location |
|---|---|---|---|---|
| limit | Optional | Integer | Maximum results per page. Range: 1-100. Default: 20. Example: "50" | Query |
| offset | Optional | Integer | Number of results to skip for pagination. Default: 0. Used with limit for pagination. | Query |
| department | Optional | String | Filter by department code. Valid: "SALES", "ENGINEERING", "FINANCE", "HR", "OPERATIONS". Example: "SALES" | Query |
| status | Optional | String | Filter by employee status. Valid: "ACTIVE", "INACTIVE", "LEAVE", "TERMINATED". Default: all statuses. | Query |
| sortBy | Optional | String | Sort field. Valid: "name", "hireDate", "department", "salary". Default: "name". Use - prefix for descending (e.g., "-hireDate") | Query |
### Request Body
[For POST/PUT/PATCH methods, document request body structure. For GET/DELETE, state "None".]
**For POST/PUT/PATCH**:
```json
{
"[property]": "[value or type]",
"[property]": "[value or type]"
}
```
**Example**:
```json
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@company.com",
"department": "ENGINEERING",
"hireDate": "2024-01-15",
"salary": 95000.00
}
```
**Field Descriptions**:
| Field Name | Requirement | Data Type | Description |
|---|---|---|---|
| [Name] | Required/Optional | [Type] | [Description with constraints, format, valid values, length, min/max] |
**Example**:
| Field Name | Requirement | Data Type | Description |
|---|---|---|---|
| firstName | Required | String | Employee's first name. Length: 1-50 characters. Alphanumeric and spaces only. |
| lastName | Required | String | Employee's last name. Length: 1-50 characters. Alphanumeric and spaces only. |
| email | Required | String | Corporate email address. Must be unique across system. Must be valid email format (RFC 5322). |
| department | Required | String | Department code. Valid: "SALES", "ENGINEERING", "FINANCE", "HR", "OPERATIONS". Example: "ENGINEERING" |
| hireDate | Optional | Date (YYYY-MM-DD) | Hire date of employee. Format: ISO 8601 date. Cannot be future date. Example: "2024-01-15" |
| salary | Optional | Decimal | Annual salary in USD. Minimum: 20000. Maximum: 10000000. Two decimal places. Example: 95000.00 |
---
## Response
### Status Codes
[Document all HTTP status codes that can be returned by this specific method.]
| Status Code | Description |
|---|---|
| [Code] | [What this status means in context of this specific operation] |
**Example for GET method**:
| Status Code | Description |
|---|---|
| 200 OK | Request successful. Response body contains employee data matching query. |
| 400 Bad Request | Invalid query parameters or malformed request. Check parameter values and format. |
| 401 Unauthorized | Authentication token missing, invalid, or expired. Obtain new token via authentication service. |
| 403 Forbidden | Authenticated but insufficient permissions. User lacks ROLE_HR_USER required for read access. |
| 404 Not Found | No employee found with specified ID (for single-resource GET). |
| 429 Too Many Requests | Rate limit exceeded. Wait for X-RateLimit-Reset time before retrying. |
| 500 Internal Server Error | Server encountered unexpected error. Contact support if issue persists. |
**Example for POST method**:
| Status Code | Description |
|---|---|
| 201 Created | Employee successfully created. Location header contains URL to new employee. Response includes created employee data. |
| 400 Bad Request | Validation failed. Check email uniqueness, required fields, field formats, and value constraints. |
| 401 Unauthorized | Authentication token missing, invalid, or expired. |
| 403 Forbidden | Insufficient permissions. Requires ROLE_HR_MANAGER or higher. |
| 409 Conflict | Employee with this email already exists. Email must be unique. |
| 500 Internal Server Error | Server error. Contact support. |
### Response Headers
| Header Name | Description | Example Value |
|---|---|---|
| [Header name] | [What this header contains] | [Example value] |
**Example**:
| Header Name | Description | Example Value |
|---|---|---|
| Content-Type | Media type of response body | `application/json` |
| X-Total-Count | Total available records (for paginated responses) | `5000` |
| X-RateLimit-Remaining | API calls remaining in rate limit window | `998` |
| Location | URL of created/modified resource (201, 200 responses) | `[https://api.example.com/v1/employees/E12346`](https://api.example.com/v1/employees/E12346`) |
| ETag | Entity tag for caching and optimistic locking | `"abc123def456"` |
### Response Body
[Document the successful response body structure.]
**For successful request**:
```json
{
"[property]": "[value]",
"[property]": "[value]"
}
```
**Example**:
```json
{
"employeeId": "E12345",
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@company.com",
"department": "ENGINEERING",
"jobTitle": "Senior Software Engineer",
"hireDate": "2020-06-01",
"salary": 120000.00,
"status": "ACTIVE",
"createdAt": "2020-06-01T09:00:00Z",
"lastModified": "2024-01-15T14:30:00Z"
}
```
---
## Examples
### Complete Request Example
[Provide full HTTP request with all headers and body.]
```http
[HTTP METHOD] [Path]?[Query Parameters] HTTP/1.1
Host: [Host from Base URI]
Authorization: Bearer [token]
Content-Type: application/json
[Additional Headers]
[Request Body (if applicable)]
```
**Example for GET**:
```http
GET /employees?limit=20&offset=0&status=ACTIVE HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
```
**Example for POST**:
```http
POST /employees HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@company.com",
"department": "ENGINEERING",
"hireDate": "2024-01-15",
"salary": 95000.00
}
```
**Example for PATCH**:
```http
PATCH /employees/E12345 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
If-Match: "abc123def456"
{
"department": "SALES",
"salary": 105000.00
}
```
### Complete Response Example (Success)
```http
HTTP/1.1 [Status Code] [Status Message]
Content-Type: application/json
[Response Headers]
[Response Body]
```
**Example for 200 OK**:
```http
HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Remaining: 998
ETag: "abc123def456"
{
"employeeId": "E12345",
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@company.com",
"department": "ENGINEERING",
"jobTitle": "Senior Software Engineer",
"hireDate": "2020-06-01",
"salary": 120000.00,
"status": "ACTIVE",
"createdAt": "2020-06-01T09:00:00Z",
"lastModified": "2024-01-15T14:30:00Z"
}
```
**Example for 201 Created**:
```http
HTTP/1.1 201 Created
Content-Type: application/json
Location: [https://api.example.com/v1/employees/E12346](https://api.example.com/v1/employees/E12346)
{
"employeeId": "E12346",
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@company.com",
"department": "ENGINEERING",
"hireDate": "2024-01-15",
"status": "ACTIVE",
"salary": 95000.00,
"createdAt": "2024-01-15T10:30:00Z"
}
```
### Error Response Examples
**Example for 400 Bad Request**:
```http
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "email",
"issue": "Email already exists",
"value": "john.doe@company.com"
},
{
"field": "salary",
"issue": "Minimum salary is 20000",
"value": "15000"
}
]
}
}
```
**Example for 404 Not Found**:
```http
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"code": "NOT_FOUND",
"message": "Employee not found",
"details": {
"resourceType": "Employee",
"providedId": "E99999"
}
}
}
```
**Example for 409 Conflict**:
```http
HTTP/1.1 409 Conflict
Content-Type: application/json
{
"error": {
"code": "DUPLICATE_EMPLOYEE",
"message": "Employee with email already exists",
"details": {
"email": "john.doe@company.com",
"existingEmployeeId": "E10001"
}
}
}
```
---
## Related Methods
- [Parent Overview](#[rest-api-resource-name])
- [Related Method 1](#[method-anchor])
- [Related Method 2](#[method-anchor])
---
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50

View File

@@ -0,0 +1,217 @@
# REST API Overview Template
## How to Use This Template
**Purpose**: Document a set of related REST API methods that apply to the same resource or service.
**When to Use**:
- Creating documentation for a REST API with multiple methods on the same resource
- Need to document common properties shared by multiple endpoints
- Want to provide an organized reference for all methods on a resource
**Instructions**:
1. Replace all [bracketed text] with your actual content
2. Remove sections marked "Optional" if not applicable to your API
3. Provide complete examples with real data
4. Ensure all HTTP methods, URIs, and status codes are accurate
5. Test all documented features before publishing
**Template Structure**:
- Title & Introduction (~100 words)
- Base Information (URI, permissions, context)
- Methods Table (all HTTP methods for the resource)
- Common Request Headers
- Common Response Headers
- Status Codes
**Token Tip**: This overview prevents repetition in detailed method docs, saving ~40% of documentation tokens while improving clarity.
---
## [Resource Name] REST API
[Provide a brief 2-3 sentence description of what this REST API does. Include:
- Main purpose of the API
- What resources or operations it manages
- Key capabilities (list, create, update, delete, etc.)
- Any special features or scope]
**Example**:
"Provides methods to retrieve, create, update, and delete employee records.
Supports querying employees by department, status, and other criteria.
Fully supports pagination, filtering, and sorting."
## Base Information
**Base URI**: `[Absolute URI where API is hosted, e.g., [https://api.example.com/v1/employees]`](https://api.example.com/v1/employees]`)
**Permissions**:
- [Read/Query operations]: [Required role, e.g., ROLE_HR_USER]
- [Write/Create operations]: [Required role, e.g., ROLE_HR_MANAGER]
- [Delete operations]: [Required role, e.g., ROLE_ADMIN]
**Example**:
- Read: ROLE_HR_USER (can list and view employees)
- Write: ROLE_HR_MANAGER (can create and modify employees)
- Delete: ROLE_ADMIN (can permanently delete employees)
**Additional Notes**:
- [Any important API usage notes, e.g., "All requests require Bearer token authentication"]
- [Pagination information, e.g., "API supports pagination with limit and offset parameters"]
- [Rate limiting info, e.g., "Rate limit: 1000 requests per hour"]
- [Special behaviors, e.g., "Soft deletes only - employee records are marked inactive, not removed"]
## Methods
The following table lists all HTTP methods available for this resource:
| HTTP Method | Action | URI |
|---|---|---|
| [GET/POST/PUT/PATCH/DELETE] | [Link to detailed method documentation](#[anchor-link]) | [Relative URI path] |
| [HTTP Method] | [Link](#[anchor]) | [Path] |
**Example**:
| HTTP Method | Action | URI |
|---|---|---|
| GET | [List All Employees](#list-all-employees) | `/employees` |
| GET | [Get Employee by ID](#get-employee-by-id) | `/employees/{employeeId}` |
| POST | [Create Employee](#create-employee) | `/employees` |
| PUT | [Update Employee (Full Replace)](#update-employee) | `/employees/{employeeId}` |
| PATCH | [Update Employee (Partial)](#update-employee-partial) | `/employees/{employeeId}` |
| DELETE | [Delete Employee](#delete-employee) | `/employees/{employeeId}` |
**Formatting Guidelines**:
- Order methods by HTTP verb (GET, POST, PUT, PATCH, DELETE)
- Make "Action" column links to detailed method documentation
- Use consistent URI naming (e.g., `{employeeId}` for path parameters)
- URI is relative to Base URI
## Common Request Headers
The following headers are used in requests to this API:
| Header Name | Required | Description |
|---|---|---|
| [Header name] | [Yes/No] | [Description with possible values and format] |
**Example**:
| Header Name | Required | Description |
|---|---|---|
| Authorization | Yes | Bearer token for authentication. Format: `Authorization: Bearer {token}`. Obtain token from authentication service. |
| Content-Type | Yes | Media type of request body. Value: `application/json`. Required for POST, PUT, PATCH requests. |
| Accept | No | Preferred response format. Value: `application/json`. Default if not specified: `application/json`. |
| X-Request-ID | No | Optional request ID for tracking and debugging. Format: UUID (e.g., `123e4567-e89b-12d3-a456-426614174000`). Any valid UUID accepted. |
| If-Match | No | ETag for optimistic locking on PUT/PATCH requests. Format: quoted string (e.g., `"abc123def456"`). Required when implementing concurrent update protection. |
**Field Descriptions**:
- **Header Name**: Exact header name (case-sensitive)
- **Required**: Yes if must be present; No if optional
- **Description**: Purpose, accepted values, format, constraints, and default values
## Common Response Headers
The following headers appear in responses from this API:
| Header Name | Description |
|---|---|
| [Header name] | [Purpose and possible values] |
**Example**:
| Header Name | Description |
|---|---|
| Content-Type | Type of response body. Always `application/json`. |
| X-Total-Count | Total number of available resources (included in paginated responses). Example: `5000` |
| X-RateLimit-Limit | Maximum API calls allowed in rate limit window. Example: `1000` |
| X-RateLimit-Remaining | Number of API calls remaining in current window. Example: `998` |
| X-RateLimit-Reset | Timestamp when rate limit resets (Unix seconds). Example: `1642123456` |
| Location | URL of newly created resource (included in 201 Created responses). Format: Absolute URL. Example: `[https://api.example.com/v1/employees/E12346`](https://api.example.com/v1/employees/E12346`) |
| ETag | Entity tag for caching and optimistic locking. Format: Quoted string. Example: `"abc123def456"` |
## Status Codes
All HTTP status codes that can be returned by methods in this API are documented below:
**Success Codes**:
| Status Code | Result Description |
|---|---|
| 200 OK | Request successful. Response body contains requested data. |
| 201 Created | Resource successfully created. Location header contains URL to new resource. Response body typically contains created object. |
| 204 No Content | Request successful. No response body returned. Typically for DELETE operations or updates with `Prefer: return=minimal`. |
**Error Codes**:
| Status Code | Result Description |
|---|---|
| 400 Bad Request | Invalid request format, syntax, or validation failure. Response body contains error details. Check request format, required fields, and parameter values. |
| 401 Unauthorized | Authentication required or authentication token invalid/expired. Obtain new token or verify Bearer token format. |
| 403 Forbidden | Authenticated but insufficient permissions for operation. Request ROLE_[appropriate role] permission assignment. |
| 404 Not Found | Requested resource doesn't exist. Verify resource ID/URI and that resource hasn't been deleted. |
| 409 Conflict | Request conflicts with current resource state (e.g., duplicate email, unique constraint violation). Resource may already exist or data constraint prevents operation. |
| 410 Gone | Resource previously existed but is now deleted. Resource cannot be recovered. |
| 429 Too Many Requests | Rate limit exceeded. See X-RateLimit-Reset header for when to retry. Implement exponential backoff. |
| 500 Internal Server Error | Server encountered unexpected error. Contact support if issue persists. |
| 503 Service Unavailable | Service temporarily unavailable (maintenance, overload). Retry after delay. See Retry-After header if present. |
**Common Error Response Body Structure**:
```json
{
"error": {
"code": "[Error code identifier]",
"message": "[Human-readable error message]",
"details": {
"[field or property]": "[specific error detail]"
}
}
}
```
---
## Additional Information
### Rate Limiting
[Document rate limiting policy if applicable]
- Limit: [requests per time period, e.g., 1000 requests per hour]
- Tracking: [Rate limit headers used for tracking]
- Handling: [What happens when limit exceeded and how to recover]
### Pagination
[Document pagination approach if applicable]
- Query Parameters: [e.g., limit and offset]
- Default Size: [default number of results]
- Maximum Size: [maximum allowed per request]
- Response Structure: [how pagination info appears in response]
### Filtering and Sorting
[Document if API supports query-based filtering/sorting]
- Filtering Syntax: [explain parameter format]
- Sortable Fields: [list fields that support sorting]
- Example: [provide sample filter/sort query]
### Error Handling Best Practices
- Always check status code before processing response body
- Implement exponential backoff for retryable errors (5xx, 429)
- Parse error response for details about what went wrong
- Log error codes and messages for debugging
- Distinguish between client errors (4xx) and server errors (5xx)
---
## Related Documentation
- [API Style Guide - Manual REST and OData Documentation](https://github.com/SAP-docs/api-style-guide)
- [OAuth 2.0 Authentication](https://oauth.net/2/)
- [HTTP Status Codes Reference (RFC 9110)](https://www.rfc-editor.org/rfc/rfc9110.html#status.codes)
**Template Version**: 1.0
**Last Updated**: 2025-11-21
**Compliance**: SAP API Style Guide Section 50