Skip to content

feat: asgi request - #2467

Merged
Lancetnik merged 3 commits into
ag2ai:mainfrom
borisalekseev:feat/asgi-request
Sep 25, 2025
Merged

Lancetnik merged 3 commits into
ag2ai:mainfrom
borisalekseev:feat/asgi-request

Conversation

@borisalekseev

@borisalekseev borisalekseev commented Aug 21, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Fixes #1798

TODO:

  • Depends tests
  • remove hasattr
  • check if possible move "Scope" to type checking import

Backward compatibility with old HTTP handlers that receive a scope argument is preserved.

Example usage:

import logging

from faststream.asgi import AsgiFastStream, get, AsgiResponse, post, Request, Header, Query
from faststream.nats import NatsBroker

logger = logging.getLogger("faststream")


@get
async def access_request(request: Request):
    logger.info("Received request %s", request)
    # Received request <faststream.asgi.request.AsgiRequest object at 0x7cda02c674d0>
    return AsgiResponse(status_code=200)


@get
async def access_query(faststream: list[str] | None = Query(default=None)):
    logger.info("Faststream is %s", faststream)
    # Faststream is ['cool']
    return AsgiResponse()


# curl -X POST http://127.0.0.1:8000/access_header --header "X-auth-token: secret-token" -d '{"field": "val"}'
@post
async def access_header(request: Request, token: str = Header("X-auth-token")):
    if token != "secret-token":
        return AsgiResponse(status_code=401)
    data = await request.json()
    logger.info(data)  # {'field': 'val'}
    return AsgiResponse(status_code=200)


broker = NatsBroker()
app = AsgiFastStream(broker, asgi_routes=[
    ("/access_request", access_request),
    ("/access_query", access_query),
])
app.mount("/access_header", access_header)

Type of change

Please delete options that are not relevant.

  • Documentation (typos, code examples, or any documentation updates)
  • Bug fix (a non-breaking change that resolves an issue)
  • New feature (a non-breaking change that adds functionality)
  • Breaking change (a fix or feature that would disrupt existing functionality)
  • This change requires a documentation update

Checklist

  • My code adheres to the style guidelines of this project (just lint shows no errors)
  • I have conducted a self-review of my own code
  • I have made the necessary changes to the documentation
  • My changes do not generate any new warnings
  • I have added tests to validate the effectiveness of my fix or the functionality of my new feature
  • Both new and existing unit tests pass successfully on my local environment by running just test-coverage
  • I have ensured that static analysis tests are passing by running just static-analysis
  • I have included code examples to illustrate the modifications

Comment thread faststream/asgi/app.py Outdated
Comment thread faststream/asgi/factories.py Outdated
Comment thread faststream/asgi/handlers.py Outdated
@borisalekseev
borisalekseev marked this pull request as ready for review August 26, 2025 09:59
@borisalekseev borisalekseev changed the title asgi request, post handler, context feat: asgi request Aug 26, 2025
Comment thread faststream/asgi/factories.py
Comment thread faststream/asgi/annotations.py Outdated
Comment thread faststream/asgi/handlers.py Outdated
):
response = await self.func(scope)
except Exception:
logger.exception("Exception occurred while processing request")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should we use this logger or from the context? Also, I suggest to add an exception traceback by logger.error(..., exc_info=exception)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Here I replaced the logger with the application logger and also added the logger forwarding to the context so it could be used in the handler.

@Lancetnik

Copy link
Copy Markdown
Member

@Sehat1137 can you review, please?

@Lancetnik
Lancetnik changed the base branch from dev to main September 4, 2025 20:51
@Sehat1137

Copy link
Copy Markdown
Collaborator

I think we need support new features into AsyncAPI schema, because right now we don't see any information about required headers or query params

@Sehat1137

Copy link
Copy Markdown
Collaborator

I think we need support new features into AsyncAPI schema, because right now we don't see any information about required headers or query params

next pr

@borisalekseev
borisalekseev marked this pull request as draft September 8, 2025 14:29
@Sehat1137
Sehat1137 marked this pull request as ready for review September 9, 2025 08:06
@borisalekseev
borisalekseev force-pushed the feat/asgi-request branch 2 times, most recently from 5746ce4 to d549237 Compare September 12, 2025 06:30
Comment thread faststream/asgi/app.py
Comment thread faststream/asgi/factories.py
Comment thread faststream/asgi/app.py Outdated
) -> None:
self.routes = list(asgi_routes)
context = context or ContextRepo()
context.set_global("app", self)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It is already set in super.__init__, there is no need to double this logic here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The problem is that I need access to context.app when registering the handler, which happens before the parent class installs the app in the context. In this case, can I change the behavior in faststream._internal.application.Application?

@Lancetnik
Lancetnik added this pull request to the merge queue Sep 25, 2025
Merged via the queue into ag2ai:main with commit f97e5f9 Sep 25, 2025
29 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.

Feature: Add DI for ASGI routes

3 participants