Skip to content

feat(request): add get_param_as_media() method#2556

Open
MannXo wants to merge 8 commits intofalconry:masterfrom
MannXo:feat/get-param-as-media
Open

feat(request): add get_param_as_media() method#2556
MannXo wants to merge 8 commits intofalconry:masterfrom
MannXo:feat/get-param-as-media

Conversation

@MannXo
Copy link
Contributor

@MannXo MannXo commented Oct 20, 2025

Summary of Changes

Adds a new public helper: Request.get_param_as_media(name, media_type=None, required=False, store=None, default=None) :
1- Deserializes a single query-string parameter using the app's configured media handlers.
2- If media_type is omitted, falls back to the app's default_media_type.
3- Stores the parsed value in store when provided.
4- Raises HTTPInvalidParam on parse errors (or when no suitable handler exists for non-JSON media).

ASGI support:
1- falcon.asgi.Request.get_param_as_media delegates to the synchronous WSGI implementation (parameter values are already in memory).
2- get_param_as_json() now delegates to get_param_as_media(..., MEDIA_JSON) (thin wrapper).

Related Issues

closes: #2549

Pull Request Checklist

This is just a reminder about the most common mistakes. Please make sure that you tick all appropriate boxes. Reading our contribution guide at least once will save you a few review cycles!

If an item doesn't apply to your pull request, check it anyway to make it apparent that there's nothing to do.

  • Applied changes to both WSGI and ASGI code paths and interfaces (where applicable).
  • Added tests for changed code.
  • Performed automated tests and code quality checks by running tox.
  • Prefixed code comments with GitHub nick and an appropriate prefix.
  • Coding style is consistent with the rest of the framework.
  • Updated documentation for changed code.
    • Added docstrings for any new classes, functions, or modules.
    • Updated docstrings for any modifications to existing code.
    • Updated both WSGI and ASGI docs (where applicable).
    • Added references to new classes, functions, or modules to the relevant RST file under docs/.
    • Updated all relevant supporting documentation files under docs/.
    • A copyright notice is included at the top of any new modules (using your own name or the name of your organization).
    • Changed/added classes/methods/functions have appropriate versionadded, versionchanged, or deprecated directives.
  • Changes (and possible deprecations) have towncrier news fragments under docs/_newsfragments/, with the file name format {issue_number}.{fragment_type}.rst. (Run tox -e towncrier, and inspect docs/_build/html/changes/ in the browser to ensure it renders correctly.)
  • LLM output, if any, has been carefully reviewed and tested by a human developer. (See also: Use of LLMs ("AI").)

If you have any questions to any of the points above, just submit and ask! This checklist is here to help you, not to deter you from contributing!

PR template inspired by the attrs project.

@codecov
Copy link

codecov bot commented Oct 23, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (002fa6c) to head (89b3f49).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #2556   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           64        64           
  Lines         7911      7920    +9     
  Branches      1086      1088    +2     
=========================================
+ Hits          7911      7920    +9     

☔ View full report in Codecov by Sentry.
📢 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

- Cover media_type=None fallback to default_media_type
- Cover JSON handler fallback when no explicit handler found
- Cover error case when no handler and non-JSON media type
- Ensures 100% coverage for new get_param_as_media method
Copy link
Member

@vytas7 vytas7 left a comment

Choose a reason for hiding this comment

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

Hi @MannXo, thanks for this PR, and sorry we have been a bit slow with reviews.

This looks good overall, but there are some details that need polishing before this could be merged (see comments inline).

raise errors.HTTPInvalidParam(msg, name)

try:
# TODO(CaselIT): find a way to avoid encode + BytesIO if handlers
Copy link
Member

Choose a reason for hiding this comment

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

Please restore @CaselIT 's comment. This is still an unsolved issue in the framework.


return self._cached_headers

def get_param_as_media(
Copy link
Member

Choose a reason for hiding this comment

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

Is there a reason for copypasting this here? Couldn't we get the exact same copy (sans extra call overhead) via inheritance?

name (str): Parameter name, case-sensitive (e.g., 'payload').

Keyword Args:
media_type (str|None): Media type to use for deserialization. If
Copy link
Member

Choose a reason for hiding this comment

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

Maybe we could use the same form (str | None) here as in the annotation (if we even need to duplicate it here? 🤔)?

if handler is None:
handler = _DEFAULT_JSON_HANDLER
# Fall back to JSON handler when requested media is JSON
if media_type and MEDIA_JSON in media_type:
Copy link
Member

Choose a reason for hiding this comment

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

We are missing the case here when media_type is omitted, and the default_media_type is JSON. It should also use the default handler for JSON according to this logic.

if handler is None:
handler = _DEFAULT_JSON_HANDLER
# Fall back to JSON handler when requested media is JSON
if media_type and MEDIA_JSON in media_type:
Copy link
Member

Choose a reason for hiding this comment

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

This is a bit sloppy way to check MEDIA_JSON in media_type, this way it could match an unrelated media type such as application/jsonbinary or whatever.

However, we do cut corners in Falcon in some edge cases like this one. But then we should add a NOTE(...): ... comment explaining this reasoning (along the lines "good enough until proven otherwise").

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.

Add new method req.get_param_as_media()

2 participants