wapiti-swagger


Namewapiti-swagger JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryA library for parsing and generating request bodies from Swagger/OpenAPI specifications.
upload_time2024-12-29 15:08:24
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords swagger openapi wapiti parser
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # **Wapiti Swagger Parser**

![License](https://img.shields.io/github/license/wapiti-scanner/wapiti_swagger)
![Python Versions](https://img.shields.io/badge/python-3.8%20|%203.9%20|%203.10%20|%203.11%20|%203.12-blue)

## **Project Description**

The **Wapiti Swagger Parser** is a Python library designed to parse Swagger (OpenAPI) specifications and extract the necessary information to generate valid HTTP requests. It focuses on providing a clean, programmatic interface for analyzing Swagger files and creating request templates without relying on external tools for OpenAPI processing.

This library is particularly useful for scenarios where only the request generation requirements are of interest, such as:

- Automated testing and validation of APIs.
- Dynamic request generation for web vulnerability scanners (like Wapiti).
- Custom API tooling.

The library is lightweight, relying only on Python's built-in `json` library and `PyYAML` for file parsing, and it avoids heavy dependencies on larger OpenAPI frameworks.

---

## **Key Features**

- **Request Extraction**:
  - Parses all HTTP requests (methods, paths, parameters) defined in the Swagger file.
- **Schema Handling**:
  - Resolves `$ref` references in schemas, including handling circular references gracefully.
- **Custom Types**:
  - Identifies and retains custom types (e.g., enumerated values, objects) for enhanced request understanding.
- **Request Body Generation**:
  - Automatically generates example request bodies based on schema definitions.
- **Metadata Extraction**:
  - Captures root-level metadata like `host`, `basePath`, `servers`, and `schemes`.
- **Supports Swagger 2.0 and OpenAPI 3.x**:
  - Works with both specification versions seamlessly.

---

## **Usage Example**

```python
from wapiti_swagger.parser import parse, generate_request_body_from_schema

# Load and parse a Swagger file
parsed = parse("swagger.json")

# List all available requests
for request in parsed.requests:
    print(request)

# Generate an example request body for a specific request (here one expecting JSON input)
request_body = generate_request_body_from_schema(
    schema=request.parameters[0].schema,  # Use the schema of the first parameter
    resolved_components=parsed.components
)
print("Example request body:", request_body)
```

---

## **Why Use This Library?**

Unlike general-purpose OpenAPI parsers, this library is optimized for specific use cases like generating valid requests for API testing, scanning, or mocking. It is lightweight, customizable, and avoids unnecessary processing of response definitions or additional metadata unrelated to request generation.

---

## **Methods in `parser` Module**

### 1. `parse(file_path: str) -> ParsedSwagger`  
Parses a Swagger/OpenAPI specification file and returns a `ParsedSwagger` object containing the following:  
- **Requests:** List of `SwaggerRequest` objects extracted from paths.
- **Components:** Preprocessed and resolved components (e.g., schemas, parameters).
- **Metadata:** High-level metadata like `host`, `basePath`, and `servers`.

**Parameters:**
- `file_path` (str): Path to the Swagger/OpenAPI file (JSON or YAML).

**Returns:**
- `ParsedSwagger`: Object containing parsed requests, components, and metadata.

---

### 2. `extract_requests(data: dict) -> List[SwaggerRequest]`  
Extracts all HTTP requests from the `paths` section of the Swagger specification.

**Parameters:**
- `data` (dict): The full Swagger/OpenAPI specification as a dictionary.

**Returns:**
- `List[SwaggerRequest]`: A list of requests with details like method, path, parameters, and request bodies.

---

### 3. `extract_request_body(request_body: dict) -> List[Parameter]`  
Extracts parameters from the `requestBody` section of a Swagger path operation.  
Handles multiple media types (e.g., `application/json`, `text/json`).

**Parameters:**
- `request_body` (dict): The `requestBody` definition for a path operation.

**Returns:**
- `List[Parameter]`: A list of parameters with details like media type, schema, and custom type.

---

### 4. `extract_parameter(param: dict) -> Parameter`  
Parses a single parameter from the `parameters` section of a Swagger path operation.

**Parameters:**
- `param` (dict): The parameter definition.

**Returns:**
- `Parameter`: Object representing the parameter with details like name, location, type, and schema.

---

### 5. `parse_components(components: dict) -> Dict[str, Dict]`  
Resolves and preprocesses all components (e.g., schemas, parameters) from the `components` section of the Swagger specification.

**Parameters:**
- `components` (dict): The `components` section of the Swagger specification.

**Returns:**
- `Dict[str, Dict]`: Resolved and preprocessed components organized by type (e.g., schemas, parameters).

---

### 6. `resolve_schema(schema: dict, resolved_components: dict, visited_refs: set) -> dict`  
Recursively resolves `$ref` references in schemas while avoiding circular references.

**Parameters:**
- `schema` (dict): The schema to resolve.
- `resolved_components` (dict): Preprocessed components for reference resolution.
- `visited_refs` (set): Tracks references to avoid circular references.

**Returns:**
- `dict`: Fully resolved schema.

---

### 7. `extract_metadata(data: dict) -> Dict[str, Any]`  
Extracts high-level metadata from the root of the Swagger specification, such as `host`, `basePath`, and `servers`.

**Parameters:**
- `data` (dict): The full Swagger/OpenAPI specification.

**Returns:**
- `Dict[str, Any]`: Metadata like `host`, `basePath`, `schemes`, and `servers`.

---

### 8. `generate_request_body_from_schema(schema: dict, resolved_components: dict) -> Optional[Union[dict, list, str, int, bool]]`  
Generates an example request body based on a schema definition.

**Parameters:**
- `schema` (dict): The schema definition.
- `resolved_components` (dict): Resolved components for reference resolution.

**Returns:**
- `Optional[Union[dict, list, str, int, bool]]`: An example request body.

---

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "wapiti-swagger",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "swagger, openapi, wapiti, parser",
    "author": null,
    "author_email": "Nicolas Surribas <nicolas.surribas@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/66/7b/a7467b5e9b7774536998b62d51413181b1483f582f41651e29ec56607b4a/wapiti_swagger-0.1.0.tar.gz",
    "platform": null,
    "description": "# **Wapiti Swagger Parser**\n\n![License](https://img.shields.io/github/license/wapiti-scanner/wapiti_swagger)\n![Python Versions](https://img.shields.io/badge/python-3.8%20|%203.9%20|%203.10%20|%203.11%20|%203.12-blue)\n\n## **Project Description**\n\nThe **Wapiti Swagger Parser** is a Python library designed to parse Swagger (OpenAPI) specifications and extract the necessary information to generate valid HTTP requests. It focuses on providing a clean, programmatic interface for analyzing Swagger files and creating request templates without relying on external tools for OpenAPI processing.\n\nThis library is particularly useful for scenarios where only the request generation requirements are of interest, such as:\n\n- Automated testing and validation of APIs.\n- Dynamic request generation for web vulnerability scanners (like Wapiti).\n- Custom API tooling.\n\nThe library is lightweight, relying only on Python's built-in `json` library and `PyYAML` for file parsing, and it avoids heavy dependencies on larger OpenAPI frameworks.\n\n---\n\n## **Key Features**\n\n- **Request Extraction**:\n  - Parses all HTTP requests (methods, paths, parameters) defined in the Swagger file.\n- **Schema Handling**:\n  - Resolves `$ref` references in schemas, including handling circular references gracefully.\n- **Custom Types**:\n  - Identifies and retains custom types (e.g., enumerated values, objects) for enhanced request understanding.\n- **Request Body Generation**:\n  - Automatically generates example request bodies based on schema definitions.\n- **Metadata Extraction**:\n  - Captures root-level metadata like `host`, `basePath`, `servers`, and `schemes`.\n- **Supports Swagger 2.0 and OpenAPI 3.x**:\n  - Works with both specification versions seamlessly.\n\n---\n\n## **Usage Example**\n\n```python\nfrom wapiti_swagger.parser import parse, generate_request_body_from_schema\n\n# Load and parse a Swagger file\nparsed = parse(\"swagger.json\")\n\n# List all available requests\nfor request in parsed.requests:\n    print(request)\n\n# Generate an example request body for a specific request (here one expecting JSON input)\nrequest_body = generate_request_body_from_schema(\n    schema=request.parameters[0].schema,  # Use the schema of the first parameter\n    resolved_components=parsed.components\n)\nprint(\"Example request body:\", request_body)\n```\n\n---\n\n## **Why Use This Library?**\n\nUnlike general-purpose OpenAPI parsers, this library is optimized for specific use cases like generating valid requests for API testing, scanning, or mocking. It is lightweight, customizable, and avoids unnecessary processing of response definitions or additional metadata unrelated to request generation.\n\n---\n\n## **Methods in `parser` Module**\n\n### 1. `parse(file_path: str) -> ParsedSwagger`  \nParses a Swagger/OpenAPI specification file and returns a `ParsedSwagger` object containing the following:  \n- **Requests:** List of `SwaggerRequest` objects extracted from paths.\n- **Components:** Preprocessed and resolved components (e.g., schemas, parameters).\n- **Metadata:** High-level metadata like `host`, `basePath`, and `servers`.\n\n**Parameters:**\n- `file_path` (str): Path to the Swagger/OpenAPI file (JSON or YAML).\n\n**Returns:**\n- `ParsedSwagger`: Object containing parsed requests, components, and metadata.\n\n---\n\n### 2. `extract_requests(data: dict) -> List[SwaggerRequest]`  \nExtracts all HTTP requests from the `paths` section of the Swagger specification.\n\n**Parameters:**\n- `data` (dict): The full Swagger/OpenAPI specification as a dictionary.\n\n**Returns:**\n- `List[SwaggerRequest]`: A list of requests with details like method, path, parameters, and request bodies.\n\n---\n\n### 3. `extract_request_body(request_body: dict) -> List[Parameter]`  \nExtracts parameters from the `requestBody` section of a Swagger path operation.  \nHandles multiple media types (e.g., `application/json`, `text/json`).\n\n**Parameters:**\n- `request_body` (dict): The `requestBody` definition for a path operation.\n\n**Returns:**\n- `List[Parameter]`: A list of parameters with details like media type, schema, and custom type.\n\n---\n\n### 4. `extract_parameter(param: dict) -> Parameter`  \nParses a single parameter from the `parameters` section of a Swagger path operation.\n\n**Parameters:**\n- `param` (dict): The parameter definition.\n\n**Returns:**\n- `Parameter`: Object representing the parameter with details like name, location, type, and schema.\n\n---\n\n### 5. `parse_components(components: dict) -> Dict[str, Dict]`  \nResolves and preprocesses all components (e.g., schemas, parameters) from the `components` section of the Swagger specification.\n\n**Parameters:**\n- `components` (dict): The `components` section of the Swagger specification.\n\n**Returns:**\n- `Dict[str, Dict]`: Resolved and preprocessed components organized by type (e.g., schemas, parameters).\n\n---\n\n### 6. `resolve_schema(schema: dict, resolved_components: dict, visited_refs: set) -> dict`  \nRecursively resolves `$ref` references in schemas while avoiding circular references.\n\n**Parameters:**\n- `schema` (dict): The schema to resolve.\n- `resolved_components` (dict): Preprocessed components for reference resolution.\n- `visited_refs` (set): Tracks references to avoid circular references.\n\n**Returns:**\n- `dict`: Fully resolved schema.\n\n---\n\n### 7. `extract_metadata(data: dict) -> Dict[str, Any]`  \nExtracts high-level metadata from the root of the Swagger specification, such as `host`, `basePath`, and `servers`.\n\n**Parameters:**\n- `data` (dict): The full Swagger/OpenAPI specification.\n\n**Returns:**\n- `Dict[str, Any]`: Metadata like `host`, `basePath`, `schemes`, and `servers`.\n\n---\n\n### 8. `generate_request_body_from_schema(schema: dict, resolved_components: dict) -> Optional[Union[dict, list, str, int, bool]]`  \nGenerates an example request body based on a schema definition.\n\n**Parameters:**\n- `schema` (dict): The schema definition.\n- `resolved_components` (dict): Resolved components for reference resolution.\n\n**Returns:**\n- `Optional[Union[dict, list, str, int, bool]]`: An example request body.\n\n---\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A library for parsing and generating request bodies from Swagger/OpenAPI specifications.",
    "version": "0.1.0",
    "project_urls": null,
    "split_keywords": [
        "swagger",
        " openapi",
        " wapiti",
        " parser"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6f8da4bc3c9892e7741e48cdc9dc9a6dbfc59bafb886656226bfbdace8c9683a",
                "md5": "5b5407c2e419eeaeeb13d16da00227a6",
                "sha256": "2c5798eacfe9bba067466bbc56448a4e9ca5047552cab7b0a8d76ac1cb186647"
            },
            "downloads": -1,
            "filename": "wapiti_swagger-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5b5407c2e419eeaeeb13d16da00227a6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 4164,
            "upload_time": "2024-12-29T15:08:21",
            "upload_time_iso_8601": "2024-12-29T15:08:21.941482Z",
            "url": "https://files.pythonhosted.org/packages/6f/8d/a4bc3c9892e7741e48cdc9dc9a6dbfc59bafb886656226bfbdace8c9683a/wapiti_swagger-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "667ba7467b5e9b7774536998b62d51413181b1483f582f41651e29ec56607b4a",
                "md5": "c51f672049acaeff5ed22c805df0fecb",
                "sha256": "78c86729fa91b23c8d26341b4ac3955d6ebed3595ae5a66bcc5a23c41f14ff8a"
            },
            "downloads": -1,
            "filename": "wapiti_swagger-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "c51f672049acaeff5ed22c805df0fecb",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 9077,
            "upload_time": "2024-12-29T15:08:24",
            "upload_time_iso_8601": "2024-12-29T15:08:24.417974Z",
            "url": "https://files.pythonhosted.org/packages/66/7b/a7467b5e9b7774536998b62d51413181b1483f582f41651e29ec56607b4a/wapiti_swagger-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-29 15:08:24",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "wapiti-swagger"
}
        
Elapsed time: 1.60552s