Skip to content

feat: make error media type configurable - #317

Merged
uniqueg merged 4 commits into
devfrom
feat/error-media-type
Oct 20, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/error-media-type

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Error responses can have another media type than application/problem+json (#315), e.g., application/json, as declared by many GA4GH API specifications.

  • Config: exceptions.media_type, default application/problem+json, so existing apps are unchanged. Only JSON media types without parameters are accepted (type/json or type/subtype+json, lowercased), as the body is always JSON; other values fail config validation.
  • Responses: all error responses use it, as they all pass through FOCA's handler (Connexion's own handlers are skipped): errors raised by app code, request validation (400), security (401), unknown routes and methods (404, 405), errors in request hooks. The header is set exactly as configured (no charset added for text/*). The body is unchanged.
  • Permissions API: its default specification declares the configured media type for its error responses (rewritten when loading, only for non-default media types). Custom specifications (api_specs) must declare it themselves.
  • Docs: "Media type" section in docs/configuration/exceptions.md, the template config, the README feature list, and a pointer in the 0.14 migration guide.

Content negotiation via Accept was rejected in the issue and is not implemented.

Closes #315.

Verification

  • pytest (unit tests, MongoDB 7.0 on port 12345): 738 passed, 100% coverage. New tests: media types for app, mapped, unmapped, validation, security, 404 and 405 errors (default, application/json, text/json); valid and invalid config values; app created from a config file; permissions API errors and its served specification end to end; spec rewrite by status.
  • ruff check, ruff format --check, mypy foca: clean. mkdocs build --strict: passes. gitleaks dir .: no leaks.
  • Not run locally: integration tests (tests/integration_tests.py, need the petstore example with Docker Compose); CI runs them.
  • Reviews (adversarial + quality, 2 rounds): fixed: permissions API spec follows the media type, exact Content-Type for text/*, simpler media type pattern, explicit test parameters, migration guide pointer, end-to-end test. Declined: validating assignments after creation (validate_assignment): no FOCA code assigns these fields, other config models don't validate assignments either, and with it a failed mapping assignment left the model unusable. Rewriting $ref responses: the default spec has none (documented in the docstring).
  • CI: all checks pass (unit tests on Python 3.10–3.14 with MongoDB 7.0, and 3.13 with 8.0; petstore integration tests; lint, type check and build; Read the Docs).
  • Sourcery: 2 findings; fixed: registering the permissions API on apps without FOCA configuration (bea2290, 738 tests, CI green again); declined: changing the media type at runtime (FOCA's configuration is fixed once the app is created).

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 20, 2026 20:09
Add `exceptions.media_type` (default `application/problem+json`, so
existing apps are unchanged) and send all error responses with it:
errors raised by app code, request validation and security errors, and
404/405 for unknown routes, which all pass through FOCA's handler. Only
JSON media types (`*/json`, `*/*+json`) without parameters are
accepted, as the body is always JSON.

Apps implementing specs that declare `application/json` for errors,
such as many GA4GH APIs, can now match them.

Closes #315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Declare the configured media type for the error responses of the
  default permissions API specification.
- Send the media type exactly as configured (no charset for `text/*`).
- Validate media types set after creation, too.
- Simplify the media type pattern, mention the option in the 0.14
  migration guide and shorten the template comment.
- Test the media types explicitly, with assignment and `text/json`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test end to end that errors of the permissions API have the configured
media type, as declared in the served specification, and check the
rewritten responses by status. Keep assignments unvalidated, as for
all other config models: with `validate_assignment`, a failed
assignment of `mapping` left the model invalid. Make the HTTP method
constant private and explain when the specification is loaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces exceptions.media_type, defaulting to application/problem+json, and applies it consistently to all FOCA-managed error responses with strict JSON media-type validation. The built-in permissions API dynamically rewrites its default specification to match non-default settings, while custom specifications remain the caller’s responsibility; documentation and comprehensive tests cover configuration, response paths, exact headers, and specification behavior.

Sequence diagram for configurable error response media types

sequenceDiagram
    participant Request
    participant Connexion
    participant FOCA as FOCA error handler
    participant App as Application

    Request->>Connexion: Handle request
    alt App or Connexion error
        Connexion-->>FOCA: exception
        FOCA->>FOCA: build_problem
        FOCA-->>Request: Response(status, JSON body, conf.media_type)
    else Unknown route or method
        Connexion-->>FOCA: 404 or 405 error
        FOCA->>FOCA: build_problem
        FOCA-->>Request: Response(status, JSON body, conf.media_type)
    end
Loading

Flow diagram for permissions API error media type configuration

flowchart TD
    Config["exceptions.media_type"] --> Register[register_permission_specs]
    Register -->|default media type| DefaultSpec[Default permissions specification]
    Register -->|non-default media type| Rewrite[_with_error_media_type]
    Rewrite --> ServedSpec[Rewritten permissions specification]
    DefaultSpec --> PermissionsAPI[Permissions API]
    ServedSpec --> PermissionsAPI
Loading

File-Level Changes

Change Details Files
Adds validated configuration for selecting the JSON media type used by every FOCA error response.
  • Introduces exceptions.media_type with a default preserving application/problem+json.
  • Validates case-insensitive JSON media types without parameters and normalizes them to lowercase.
  • Applies the exact configured value to error Content-Type headers while leaving problem-detail bodies unchanged.
  • Covers application, mapped and unmapped exceptions, validation, security, routing, configuration-file, and header behavior tests.
foca/models/config.py
foca/errors/exceptions.py
tests/models/test_config.py
tests/errors/test_errors.py
tests/test_foca.py
Keeps the built-in permissions API specification aligned with the configured error media type.
  • Rewrites default permissions API 4xx/5xx response content declarations when a non-default media type is configured.
  • Leaves custom specifications unchanged, requiring them to declare their own media type.
  • Adds specification transformation, registration, served-specification, and end-to-end response tests.
foca/security/access_control/register_access_control.py
tests/security/access_control/test_register_access_control.py
tests/test_foca.py
Documents configuration, specification requirements, and migration behavior for configurable error media types.
  • Documents accepted values, unchanged JSON bodies, lack of Accept negotiation, and permissions API behavior.
  • Updates the template configuration, README feature list, and 0.14 migration guidance.
docs/configuration/exceptions.md
templates/config.yaml
README.md
docs/migration-0.14.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (14d7e65) to head (bea2290).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #317   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1394      1423   +29     
=========================================
+ Hits          1394      1423   +29     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 20, 2026 18:51

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="168" />
<code_context>
     Returns:
         Connexion app with updated permission specifications.
     """
+    media_type = get_app_config(app.app).exceptions.media_type
+    specification: Path | dict
     if access_control_config.api_specs is None:
</code_context>
<issue_to_address>
**Permission API contract becomes stale**

When the default permissions API is registered and its media type is later changed, `register_permission_specs` rewrites the served specification once, while the exception handler reads the mutable config for each response. After the media type changes, errors use the new type but the specification still advertises the old one, so clients see a contract mismatch.

Keep the media type used by the served specification synchronized with the value the exception handler reads, or make both use the same immutable value.

Also at `foca/errors/exceptions.py:230`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/register_access_control.py" line_range="168" />
<code_context>
     Returns:
         Connexion app with updated permission specifications.
     """
+    media_type = get_app_config(app.app).exceptions.media_type
+    specification: Path | dict
     if access_control_config.api_specs is None:
</code_context>
<issue_to_address>
**Standalone spec registration now fails**

When a caller passes an unconfigured Connexion app, including when it supplies a custom `api_specs`, `get_app_config(app.app)` raises `RuntimeError` before `register_permission_specs` checks whether a custom specification was supplied, so callers without FOCA configuration cannot register that specification.

Only look up FOCA configuration when needed to rewrite the default specification, using the default media type if no FOCA configuration is attached.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/security/access_control/register_access_control.py:168, foca/security/access_control/register_access_control.py:168


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Read the error media type only for the default specification, and use
the default media type for apps without FOCA configuration, so that
`register_permission_specs()` works for them as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 791b390 into dev Oct 20, 2026
13 checks passed
@uniqueg
uniqueg deleted the feat/error-media-type branch October 20, 2026 19:01
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.

1 participant