Skip to content

Add guide for writing custom Python policies#1931

Merged
renuka-fernando merged 1 commit into
wso2:mainfrom
sehan-dissanayake:custom-policies-docs
May 20, 2026
Merged

Add guide for writing custom Python policies#1931
renuka-fernando merged 1 commit into
wso2:mainfrom
sehan-dissanayake:custom-policies-docs

Conversation

@sehan-dissanayake
Copy link
Copy Markdown
Contributor

Fix #1705

Purpose

Introduce a new step-by-step guide (docs/gateway/policies/writing-custom-python-policies.md) that explains how to author, package, and build Python policies for the gateway, including examples, SDK usage, directory layout, requirements handling, build/register instructions, best practices, and troubleshooting. Update docs/gateway/README.md and docs/gateway/policy-languages-and-runtimes.md to link to the new guide and surface it in the next-steps/navigation.

Introduce a new step-by-step guide (docs/gateway/policies/writing-custom-python-policies.md) that explains how to author, package, and build Python policies for the gateway, including examples, SDK usage, directory layout, requirements handling, build/register instructions, best practices, and troubleshooting. Update docs/gateway/README.md and docs/gateway/policy-languages-and-runtimes.md to link to the new guide and surface it in the next-steps/navigation.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

Review Change Stack

📝 Walkthrough

Summary

Added comprehensive documentation for authoring custom Python policies for the API Platform Gateway, addressing issue #1705.

Changes

New Guide: docs/gateway/policies/writing-custom-python-policies.md (830 lines)

  • Complete step-by-step guide covering policy creation, packaging, and deployment
  • Prerequisites overview (Python 3.10+, ap CLI, Docker, gateway release archive)
  • Policy directory structure and file organization
  • Detailed explanation of policy-definition.yaml with field reference and JSON Schema parameter definitions
  • Implementation guide for policy.py including required imports, logging, policy base class selection (request/response, header/body, streaming vs. buffered hooks), and the get_policy() factory function
  • Code examples for common policy types (request/response body transformation, header modification, streaming with buffered fallback)
  • Requirements management via requirements.txt with version-pinning guidance
  • Quick-reference tables for return values and execution context objects
  • Build and registration instructions for integrating policies with build.yaml
  • End-to-end example showing a policy that uppercases JSON fields with error handling
  • Best practices and troubleshooting guidance

Updated: docs/gateway/README.md

  • Added table entry linking to the new "Writing Custom Python Policies" guide

Updated: docs/gateway/policy-languages-and-runtimes.md

  • Added direct "Ready to write a custom Python policy?" link in the Python policies section
  • Added "Next Steps" section with navigation links to custom policy writing and gateway customization topics

Impact

Enables users to implement custom Python gateway policies by providing actionable documentation with examples, schema definitions, and best practices. Improves discoverability through updated documentation index and navigation links.

Walkthrough

This pull request adds a complete documentation guide for writing custom Python policies in the API Platform Gateway. The changes include a new comprehensive guide page covering prerequisites, policy directory structure, step-by-step implementation instructions (policy-definition.yaml schema, policy.py code structure, dependencies, and registration), reference tables for context objects and return types, an end-to-end example, best practices, and troubleshooting. Navigation links are added to existing documentation pages to surface this new resource.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description addresses the primary purpose and references the linked issue, but lacks details on goals, approach, testing, security checks, and other template sections. Expand the description to include Goals, Approach, Testing, Security checks, and other relevant template sections to provide complete context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding documentation for writing custom Python policies.
Linked Issues check ✅ Passed The PR fully addresses issue #1705 by delivering comprehensive documentation on authoring, packaging, and building Python policies for the gateway.
Out of Scope Changes check ✅ Passed All changes are directly related to documenting custom Python policies and updating navigation; no unrelated changes are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
docs/gateway/policies/writing-custom-python-policies.md (2)

472-488: 💤 Low value

Consider adding type hints to the get_policy() signature for consistency.

Throughout the guide, policy hook methods use explicit type hints (e.g., params: dict[str, Any]). For consistency and to reinforce best practices, consider adding type hints to the get_policy() factory function signature.

♻️ Suggested enhancement
-def get_policy(metadata, params):
+def get_policy(metadata, params: dict[str, Any]):
     """Factory function — called by the Python executor to create the policy.

Note: If the metadata type is available in the SDK, include it as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/gateway/policies/writing-custom-python-policies.md` around lines 472 -
488, The get_policy factory function lacks type hints; update the signature of
get_policy to include types for metadata and params and a return type (e.g., def
get_policy(metadata: PolicyMetadata, params: dict[str, Any]) -> MyPolicy:) using
the SDK's PolicyMetadata type if available and the concrete policy class
(MyPolicy) as the return type so it matches the other annotated hooks and
reinforces best practices.

24-29: 💤 Low value

Consider adding a language specifier to the code fence.

For better rendering and accessibility, the directory structure code block should specify a language identifier (e.g., text or bash).

📝 Suggested fix
-```
+```text
 my-policy/
 ├── policy-definition.yaml   # Identity, version, and parameter schema
 ├── policy.py                # Policy implementation (entry point)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/gateway/policies/writing-custom-python-policies.md` around lines 24 -
29, Update the fenced directory-structure block that starts with "my-policy/" in
writing-custom-python-policies.md to include a language specifier (e.g., change
the opening ``` to ```text) so the tree renders properly; keep the content
unchanged and only modify the opening fence for the code block that contains the
"my-policy/" directory listing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@docs/gateway/policies/writing-custom-python-policies.md`:
- Around line 472-488: The get_policy factory function lacks type hints; update
the signature of get_policy to include types for metadata and params and a
return type (e.g., def get_policy(metadata: PolicyMetadata, params: dict[str,
Any]) -> MyPolicy:) using the SDK's PolicyMetadata type if available and the
concrete policy class (MyPolicy) as the return type so it matches the other
annotated hooks and reinforces best practices.
- Around line 24-29: Update the fenced directory-structure block that starts
with "my-policy/" in writing-custom-python-policies.md to include a language
specifier (e.g., change the opening ``` to ```text) so the tree renders
properly; keep the content unchanged and only modify the opening fence for the
code block that contains the "my-policy/" directory listing.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8f91856b-491f-4769-9ec1-2d27483b5552

📥 Commits

Reviewing files that changed from the base of the PR and between 7bcef00 and 362bd5f.

📒 Files selected for processing (3)
  • docs/gateway/README.md
  • docs/gateway/policies/writing-custom-python-policies.md
  • docs/gateway/policy-languages-and-runtimes.md

@renuka-fernando renuka-fernando self-assigned this May 11, 2026
@renuka-fernando renuka-fernando merged commit 574afd6 into wso2:main May 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Task]: Docs for Custom Python Policies

2 participants