question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Need help tracking API usage

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Callable
from fastapi import Request, Response, Depends
from fastapi.routing import APIRoute
from server.routes.users import fastapi_users
from server.models.users import *

class session_log(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request,
        user: User = fastapi_users.get_current_user
        ) -> Response:
            response: Response = await original_route_handler(request)
            # print(f"route response: {response}")
            try:
                print("User", str(user))
            except Exception as e:
                print(f"Error : {e}")
            return response

        return custom_route_handler

Description

Hi, I’m looking for a way to track api usage on user basis. We are using fastapi-users for user management. Can anyone please suggest a way to do this. I tried using a custom API Router but was unable to fetch user details as it done through dependency injection and I kept getting errors like Depends object has no attribute ID/ Depends object is not subscriptable.

Any help would be greatly appreciated.

Thank you!!

Operating System

Linux

Operating System Details

No response

FastAPI Version

fastapi==0.61.1

Python Version

3.8

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:19

github_iconTop GitHub Comments

2reactions
AlrasheedAcommented, Feb 6, 2022

If you need to wait for the response, I would add a middleware for logging. For user info, starlette allows you attach states to the request object, which you can then access from the middleware. Not sure if there is a downside to using this with FastAPI, but the following example runs correctly.

from fastapi import FastAPI, Depends, Request

async def user_dep() -> int:
    user = 0
    return user

async def add_request_state(request: Request, user: int = Depends(user_dep)):
    request.state.user = user

app = FastAPI(dependencies=[Depends(add_request_state)])

@app.middleware("http")
async def add_logs(request: Request, call_next):
    response = await call_next(request)
    print ("some logging logic for user", request.state.user)
    print ("response status code: ", response.status_code)
    return response


@app.get("/test")
async def logged(user: int=Depends(user_dep)):
    return user

# Test behavior
from fastapi.testclient import TestClient
client = TestClient(app)
client.get('/test')

some logging logic for user 0 response status code: 200

1reaction
upeshphablecommented, Feb 8, 2022

@ari-jain013 Please close the issue if it worked.

Read more comments on GitHub >

github_iconTop Results From Across the Web

What are some good ways to track API usage? - Quora
Find the a common level of the API call on the request and/or response methods, and put some very fast logging mechanism on...
Read more >
How to Track Number of API Calls Made by Each Partner or ...
How to track how many API requests each partner or customer is hitting your API with.
Read more >
What is API Analytics? (and how to Track API Usage) - RapidAPI
First, to track API analytics across APIs you need to sign up for RapidAPI for Teams. Visit RapidAPI and select Create Organization in...
Read more >
12 Best REST API Monitoring Tools - Comparitech
We review & rank 12 of the best REST API monitoring tools to help you choose which monitor is right for you, and...
Read more >
Track API Usage - ReadMe Documentation
This chart allows you to dig into who's using your API and see how that's changing over time — a key metric for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found