# Fetching User in Protected Routes

* First we need access to our database in order to get the ID

```python
from sqlalchemy.orm import Session
from . import schemas, database
from fastapi.security import OAuth2PasswordBearer

# Now we can make requests to the Database
def verify_access_token(token: str, credentials_exception):

    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        id: str = payload.get("user_id")

        if str(id) is None:
            raise credentials_exception
        
        token_data = schemas.TokenData(id=id)

    except JWTError:
        raise credentials_exception

    return token_data

def get_current_user(token: str = Depends(oath2_scheme), db: Session =  Depends(database.get_db)):
    credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Could not validate cedentials", headers={"WWW-Authenticate": "Bearer"})

    # Fetch current user
    token = verify_access_token(token, credentials_exception)
    user = db.query(UserModels.User).filter(UserModels.User.id == token.id).first()

    return user
```

* Next step is to update the <mark style="color:orange;">`user_id`</mark> in the <mark style="color:green;">`posts.py`</mark> file

```python
@router.delete("/delete/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(id: int, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
```

* We've updated <mark style="color:orange;">`user_id`</mark> to <mark style="color:orange;">`current_user`</mark>
* This is generarly good practice for readability&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.arkannis.net/programming/python/frameworks/fastapi/fetching-user-in-protected-routes.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
