DEV Community

Cover image for How to Access the Request Object in Mitsuki Controllers
David Landup
David Landup

Posted on

How to Access the Request Object in Mitsuki Controllers

In Mitsuki, you'd usually work abstractions like @QueryParam and RequestBody that handle the details of HTTP requests for you. However, sometimes you need to access the raw request object to read headers, inspect client details, or manage cookies.

This guide shows you how to directly access the underlying starlette.requests.Request object in your controller methods.

The Request Type Hint

The easiest way to get the request object is to add a parameter to your controller method and type-hint it as Request. Mitsuki's dependency injection system will automatically provide the object for you.

Here’s how you can inject the request to read its properties:

from mitsuki import RestController, GetMapping
from starlette.requests import Request

@RestController("/api")
class HomeController:
    @GetMapping("/info")
    # The : Request type-hinted object is resolved via Mitsuki's DI
    async def get_request_info(self, request: Request) -> dict:
        return {
            "user_agent": request.headers.get("User-Agent", "Unknown"),
            "client_host": request.client.host,
            "client_port": request.client.port,
            "cookies": request.cookies,
            "path": request.url.path,
        }
Enter fullscreen mode Exit fullscreen mode

Because Mitsuki is built on Starlette, the injected object is a standard starlette.requests.Request instance, giving you access to its features.

Combining with Other Parameters

Injecting the request object doesn't interfere with Mitsuki's other features. You can combine it with path variables, query parameters, and request bodies:

from mitsuki import RestController, GetMapping, QueryParam
from starlette.requests import Request

@RestController("/api/users")
class UserController:
    @GetMapping("/{user_id}")
    async def get_user_and_log_ip(
        self,
        request: Request,
        user_id: int,
        verbose: bool = QueryParam(default=False)
    ) -> dict:
        # Log the client's IP address for auditing purposes... or whatever.
        logger.info(f"Request for user {user_id} received from IP: {request.client.host}")

        # Your regular business logic
        user = await self.service.get_user(user_id)

        return user
Enter fullscreen mode Exit fullscreen mode

Next Steps

  • Explore the docs: For more on how requests are being handled, controllers work, etc. check out the official Mitsuki Controllers documentation.

Happy coding! ❀

Top comments (0)