Skip to content

Adding more documentation - #16

Merged
tkausch merged 5 commits into
mainfrom
AddingMoreDocumentation
Nov 17, 2025
Merged

Adding more documentation#16
tkausch merged 5 commits into
mainfrom
AddingMoreDocumentation

Conversation

@tkausch

@tkausch tkausch commented Nov 10, 2025

Copy link
Copy Markdown
Owner

User description

Adding extended DocC documentation


PR Type

Documentation


Description

  • Comprehensive DocC documentation for RestError with detailed case descriptions

  • New HTTPUtil extension with documentation and usage examples

  • Configuration guide article covering RestOptions and common patterns

  • Error handling guide with recovery strategies and best practices

  • Interceptors guide demonstrating built-in and custom interceptor usage

  • Getting started guide for package integration and basic usage

  • Main package documentation with overview and topic organization


Diagram Walkthrough

flowchart LR
  A["Documentation Files"] --> B["RestError.swift"]
  A --> C["HTTPUtil.swift"]
  A --> D["Configuration.md"]
  A --> E["ErrorHandling.md"]
  A --> F["Interceptors.md"]
  A --> G["GettingStarted.md"]
  A --> H["SwiftRestRequests.md"]
  B -- "Enhanced error cases" --> I["Detailed descriptions"]
  C -- "Utility functions" --> I
  D -- "Configuration patterns" --> I
  E -- "Error recovery" --> I
  F -- "Interceptor usage" --> I
  G -- "Package setup" --> I
  H -- "Framework overview" --> I
Loading

File Walkthrough

Relevant files
Documentation
RestError.swift
Enhanced RestError documentation with detailed case descriptions

Sources/SwiftRestRequests/RestError.swift

  • Expanded documentation for RestError enum with comprehensive overview
    section
  • Added detailed descriptions for each error case with parameter
    documentation
  • Included usage examples demonstrating error handling patterns
  • Enhanced parameter descriptions with context about when errors occur
  • Added notes about configuration options and recovery strategies
+119/-16
HTTPUtil.swift
Added HTTPUtil documentation with usage examples                 

Sources/SwiftRestRequests/Documentation.docc/HTTPUtil.swift

  • Created new documentation extension for HTTPUtil class
  • Organized utility functions into logical topic groups
  • Added code examples for status code validation and content type
    handling
  • Documented status code checking, response validation, and MIME type
    handling
+42/-0   
Configuration.md
Configuration guide for RestOptions and request customization

Sources/SwiftRestRequests/Documentation.docc/Articles/Configuration.md

  • Created comprehensive configuration guide for RestOptions
  • Documented basic options including timeout, headers, and status codes
  • Provided examples for query parameters and content type configuration
  • Included security configuration patterns for certificate pinning and
    TLS
  • Demonstrated per-request options and option combining strategies
+135/-0 
ErrorHandling.md
Error handling guide with recovery strategies and patterns

Sources/SwiftRestRequests/Documentation.docc/Articles/ErrorHandling.md

  • Created error handling guide covering common error scenarios
  • Documented network errors, data processing errors, and API errors
  • Provided retry logic and graceful degradation strategies
  • Included best practices for custom error handling and error logging
  • Demonstrated error recovery patterns with code examples
+159/-0 
Interceptors.md
Interceptors guide with built-in and custom examples         

Sources/SwiftRestRequests/Documentation.docc/Articles/Interceptors.md

  • Created guide for using and creating interceptors
  • Documented built-in interceptors including LogNetworkInterceptor and
    AuthorizerInterceptor
  • Provided examples for creating custom request and response
    interceptors
  • Included best practices for error handling and thread safety in
    interceptors
  • Demonstrated interceptor chaining and composition patterns
+130/-0 
GettingStarted.md
Getting started guide for package integration and setup   

Sources/SwiftRestRequests/Documentation.docc/Articles/GettingStarted.md

  • Created getting started guide for package integration
  • Documented Swift Package Manager setup and dependency configuration
  • Provided example of creating a RestApiCaller subclass
  • Included request customization with RestOptions
  • Demonstrated error handling patterns for common scenarios
+85/-0   
SwiftRestRequests.md
Main package documentation with framework overview             

Sources/SwiftRestRequests/Documentation.docc/SwiftRestRequests.md

  • Created main package documentation with overview and features
  • Organized topics into logical sections: Essentials, Authentication,
    Interception, Serialization
  • Documented key features including async/await support and error
    handling
  • Listed all major types and protocols available in the framework
  • Provided platform and Swift version compatibility information
+50/-0   

@qodo-code-review

qodo-code-review Bot commented Nov 10, 2025

Copy link
Copy Markdown

PR Compliance Guide 🔍

(Compliance updated until commit 2fe82ab)

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status:
Sensitive Exposure: The logging example prints response URL, status, underlying error, and raw data content
directly, which can leak internal details and sensitive information to end users or
insecure logs.

Referred Code
```swift
class ErrorLogger {
    static func log(_ error: RestError) {
        switch error {
        case .malformedResponse(let response, let data, let error):
            print("""
                Failed to process response:
                URL: \(response.url?.absoluteString ?? "unknown")
                Status: \(response.statusCode)
                Error: \(error)
                Data: \(String(data: data, encoding: .utf8) ?? "invalid data")
                """)
        // Handle other cases...
        }
    }
}

</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td><details>
<summary><strong>Generic: Secure Logging Practices</strong></summary><br>

**Objective:** To ensure logs are useful for debugging and auditing without exposing sensitive <br>information like PII, PHI, or cardholder data.<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-7075ede1404773848bb491c848475ac5623a5d9021d207847ba678e70d8df603R132-R148'><strong>Insecure Logging</strong></a>: The example logger emits full URL, status, underlying error, and raw response body to logs <br>without redaction or structuring, risking sensitive data exposure and unstructured <br>logging.<br>
<details open><summary>Referred Code</summary>

```markdown
```swift
class ErrorLogger {
    static func log(_ error: RestError) {
        switch error {
        case .malformedResponse(let response, let data, let error):
            print("""
                Failed to process response:
                URL: \(response.url?.absoluteString ?? "unknown")
                Status: \(response.statusCode)
                Error: \(error)
                Data: \(String(data: data, encoding: .utf8) ?? "invalid data")
                """)
        // Handle other cases...
        }
    }
}

</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td rowspan=3>⚪</td>
<td><details>
<summary><strong>Generic: Comprehensive Audit Trails</strong></summary><br>

**Objective:** To create a detailed and reliable record of critical system actions for security analysis <br>and compliance.<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-df55dd99d031da841aa19e4da79137ae8df05d969d1218d2d8cb26d682e82187R1-R130'><strong>Missing Audit Logs</strong></a>: The added code is documentation-only and introduces no logging of critical actions, so it <br>neither violates nor satisfies audit trail requirements based on the diff alone.<br>
<details open><summary>Referred Code</summary>

```markdown
# Working with Interceptors

Learn how to use and create custom interceptors in SwiftRestRequests.

## Overview

Interceptors provide a powerful way to modify requests and responses in SwiftRestRequests. They can be used for logging, authentication, request modification, and response processing.

## Built-in Interceptors

### LogNetworkInterceptor

The ``LogNetworkInterceptor`` provides detailed logging of network requests and responses:

```swift
let api = RestApiCaller()
api.addInterceptor(LogNetworkInterceptor())

AuthorizerInterceptor

... (clipped 109 lines)


</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td><details>
<summary><strong>Generic: Robust Error Handling and Edge Case Management</strong></summary><br>

**Objective:** Ensure comprehensive error handling that provides meaningful context and graceful <br>degradation<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-7075ede1404773848bb491c848475ac5623a5d9021d207847ba678e70d8df603R1-R159'><strong>Example Robustness</strong></a>: New content is documentation and examples only; while examples show handling of decoding, <br>status, and network errors, no executable changes ensure edge-case handling in production <br>code.<br>
<details open><summary>Referred Code</summary>

```markdown
# Error Handling Guide

Learn how to handle errors effectively in SwiftRestRequests.

## Overview

SwiftRestRequests provides comprehensive error handling through the ``RestError`` type. This guide explains common error scenarios and how to handle them effectively.

## Common Error Types

### Network Errors

```swift
do {
    let response = try await api.get("https://api.example.com/data")
} catch RestError.badResponse(let response, let data) {
    print("Invalid response: \(response)")
    // Handle invalid response format
} catch RestError.networkError(let error) {
    // Handle network connectivity issues
    if let urlError = error as? URLError {


 ... (clipped 138 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Validation Example: Documentation introduces interceptor examples including validation and metrics but does
not add code enforcing input validation or secure data handling in the library itself.

Referred Code
## Best Practices

### Error Handling

```swift
class ValidationInterceptor: RequestInterceptor {
    func intercept(_ request: URLRequest) throws -> URLRequest {
        guard let url = request.url else {
            throw RestError.invalidURL
        }

        // Perform validation
        guard isValid(url) else {
            throw CustomError.invalidEndpoint
        }

        return request
    }
}

... (clipped 17 lines)


</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>

<tr><td align="center" colspan="2">

<!-- placeholder --> <!-- /compliance --update_compliance=true -->

</td></tr></tbody></table>
<details><summary>Compliance status legend</summary>
🟢 - Fully Compliant<br>
🟡 - Partial Compliant<br>
🔴 - Not Compliant<br>
⚪ - Requires Further Human Verification<br>
🏷️ - Compliance label<br>
</details>

___

#### Previous compliance checks

<details>
<summary>Compliance check up to commit <a href='https://github.com/tkausch/SwiftRestRequests/commit/e2cbbaf0ac812d6177f1d5fcdd5f31db43019316'>e2cbbaf</a></summary><br>
<table><tbody><tr><td colspan='2'><strong>Security Compliance</strong></td></tr>
<tr><td>🟢</td><td><details><summary><strong>No security concerns identified</strong></summary>
No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
</details></td></tr>
<tr><td colspan='2'><strong>Ticket Compliance</strong></td></tr>
<tr><td>⚪</td><td><details><summary>🎫 <strong>No ticket provided </summary></strong>


- [ ] Create ticket/issue <!-- /create_ticket --create_ticket=true -->

</details></td></tr>
<tr><td colspan='2'><strong>Codebase Duplication Compliance</strong></td></tr>
<tr><td>⚪</td><td><details><summary><strong>Codebase context is not defined </strong></summary>


Follow the <a href='https://qodo-merge-docs.qodo.ai/core-abilities/rag_context_enrichment/'>guide</a> to enable codebase context checks.

</details></td></tr>
<tr><td colspan='2'><strong>Custom Compliance</strong></td></tr>
<tr><td rowspan=3>🟢</td><td>
<details><summary><strong>Generic: Comprehensive Audit Trails</strong></summary><br>

**Objective:** To create a detailed and reliable record of critical system actions for security analysis <br>and compliance.<br>

**Status:** Passed<br>


> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td>
<details><summary><strong>Generic: Meaningful Naming and Self-Documenting Code</strong></summary><br>

**Objective:** Ensure all identifiers clearly express their purpose and intent, making code <br>self-documenting<br>

**Status:** Passed<br>


> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td>
<details><summary><strong>Generic: Security-First Input Validation and Data Handling</strong></summary><br>

**Objective:** Ensure all data inputs are validated, sanitized, and handled securely to prevent <br>vulnerabilities<br>

**Status:** Passed<br>


> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td rowspan=2>🔴</td>
<td><details>
<summary><strong>Generic: Secure Error Handling</strong></summary><br>

**Objective:** To prevent the leakage of sensitive system information through error messages while <br>providing sufficient detail for internal debugging.<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-7075ede1404773848bb491c848475ac5623a5d9021d207847ba678e70d8df603R132-R148'><strong>Sensitive Logging</strong></a>: The logging example prints response URL, status, raw error, and response body directly <br>which can expose sensitive information to users or unsecured logs.<br>
<details open><summary>Referred Code</summary>

```markdown
```swift
class ErrorLogger {
    static func log(_ error: RestError) {
        switch error {
        case .malformedResponse(let response, let data, let error):
            print("""
                Failed to process response:
                URL: \(response.url?.absoluteString ?? "unknown")
                Status: \(response.statusCode)
                Error: \(error)
                Data: \(String(data: data, encoding: .utf8) ?? "invalid data")
                """)
        // Handle other cases...
        }
    }
}

</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td><details>
<summary><strong>Generic: Secure Logging Practices</strong></summary><br>

**Objective:** To ensure logs are useful for debugging and auditing without exposing sensitive <br>information like PII, PHI, or cardholder data.<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-7075ede1404773848bb491c848475ac5623a5d9021d207847ba678e70d8df603R132-R148'><strong>PII Risk In Logs</strong></a>: The example logger outputs raw response data and full URLs which may include PII or <br>secrets and is not structured logging.<br>
<details open><summary>Referred Code</summary>

```markdown
```swift
class ErrorLogger {
    static func log(_ error: RestError) {
        switch error {
        case .malformedResponse(let response, let data, let error):
            print("""
                Failed to process response:
                URL: \(response.url?.absoluteString ?? "unknown")
                Status: \(response.statusCode)
                Error: \(error)
                Data: \(String(data: data, encoding: .utf8) ?? "invalid data")
                """)
        // Handle other cases...
        }
    }
}

</details>

> Learn more about managing compliance <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#configuration-options'>generic rules</a> or creating your own <a href='https://qodo-merge-docs.qodo.ai/tools/compliance/#custom-compliance'>custom rules</a>
</details></td></tr>
<tr><td rowspan=1>⚪</td>
<td><details>
<summary><strong>Generic: Robust Error Handling and Edge Case Management</strong></summary><br>

**Objective:** Ensure comprehensive error handling that provides meaningful context and graceful <br>degradation<br>

**Status:** <br><a href='https://github.com/tkausch/SwiftRestRequests/pull/16/files#diff-7075ede1404773848bb491c848475ac5623a5d9021d207847ba678e70d8df603R12-R31'><strong>Inaccurate Examples</strong></a>: The documentation adds sample code referencing non-existent cases like <br><code>RestError.networkError</code> and <code>RestError.invalidURL</code>, which may mislead implementers about <br>available error handling paths.<br>
<details open><summary>Referred Code</summary>

```markdown

```swift
do {
    let response = try await api.get("https://api.example.com/data")
} catch RestError.badResponse(let response, let data) {
    print("Invalid response: \(response)")
    // Handle invalid response format
} catch RestError.networkError(let error) {
    // Handle network connectivity issues
    if let urlError = error as? URLError {
        switch urlError.code {
        case .notConnectedToInternet:
            // Handle no internet connection
        case .timedOut:
            // Handle request timeout
        default:
            // Handle other network errors
        }
    }
}

Learn more about managing compliance generic rules or creating your own custom rules

@qodo-code-review

qodo-code-review Bot commented Nov 10, 2025

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Correct an invalid property name

In the GettingStarted.md file, correct the property name from
options.httpHeaders to options.headers to match the API and other documentation.

Sources/SwiftRestRequests/Documentation.docc/Articles/GettingStarted.md [56-58]

 var options = RestOptions()
-options.httpHeaders = ["X-Test": "demo"]
+options.headers = ["X-Test": "demo"]
 options.expectedStatusCodes = [200, 204]
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies an incorrect property name (httpHeaders) in the "Getting Started" guide that would cause a compilation error, preventing users from following the example.

Medium
Fix unreachable code in retry logic

Refactor the retryableRequest example to remove an unreachable throw statement
and improve the retry logic to correctly handle the final attempt.

Sources/SwiftRestRequests/Documentation.docc/Articles/ErrorHandling.md [77-91]

 func retryableRequest<T: Decodable>(maxAttempts: Int = 3) async throws -> T {
-    var attempts = 0
+    var lastError: Error?
     
-    while attempts < maxAttempts {
+    for attempt in 1...maxAttempts {
         do {
             return try await api.get("https://api.example.com/data")
-        } catch RestError.networkError(let error) {
-            attempts += 1
-            if attempts == maxAttempts { throw error }
-            try await Task.sleep(nanoseconds: UInt64(pow(2.0, Double(attempts))) * 1_000_000_000)
+        } catch let error as RestError where error.isRetryable {
+            lastError = error
+            if attempt < maxAttempts {
+                try await Task.sleep(nanoseconds: UInt64(pow(2.0, Double(attempt))) * 1_000_000_000)
+            }
+        } catch {
+            // Non-retryable error, rethrow immediately
+            throw error
         }
     }
     
-    throw RestError.networkError(NSError(domain: "", code: -1))
+    throw lastError ?? RestError.networkError(NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Request failed after \(maxAttempts) attempts."]))
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies unreachable code in a documentation example, which is a logical flaw that would confuse users and be flagged by a compiler.

Low
General
Provide a complete response time example

Enhance the MetricsInterceptor example by implementing response time calculation
using a RequestInterceptor and a thread-safe actor to store start times.

Sources/SwiftRestRequests/Documentation.docc/Articles/Interceptors.md [52-64]

-class MetricsInterceptor: ResponseInterceptor {
-    func intercept(_ response: URLResponse, data: Data) throws {
+actor MetricsCollector {
+    private var startTimes: [URLRequest: Date] = [:]
+
+    func started(request: URLRequest) {
+        startTimes[request] = Date()
+    }
+
+    func finished(request: URLRequest) -> TimeInterval? {
+        guard let startTime = startTimes.removeValue(forKey: request) else {
+            return nil
+        }
+        return Date().timeIntervalSince(startTime)
+    }
+}
+
+class MetricsInterceptor: RequestInterceptor, ResponseInterceptor {
+    private let collector: MetricsCollector
+
+    init(collector: MetricsCollector) {
+        self.collector = collector
+    }
+
+    func intercept(_ request: URLRequest) throws -> URLRequest {
+        Task { await collector.started(request: request) }
+        return request
+    }
+    
+    func intercept(_ response: URLResponse, data: Data, for request: URLRequest) async throws {
         guard let httpResponse = response as? HTTPURLResponse else { return }
         
-        let metrics = [
+        let responseTime = await collector.finished(request: request)
+
+        let metrics: [String: Any] = [
             "status_code": httpResponse.statusCode,
-            "response_time": // Calculate response time
+            "response_time": responseTime ?? -1,
             "content_length": data.count
         ]
         
         // Log or process metrics
+        print("Request metrics: \(metrics)")
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion provides a more complete and practical implementation for the MetricsInterceptor example by showing how to calculate response time, which enhances the documentation's quality.

Low
  • Update

@tkausch
tkausch merged commit d92b56f into main Nov 17, 2025
@tkausch
tkausch deleted the AddingMoreDocumentation branch November 17, 2025 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant