Skip to content
This repository was archived by the owner on Mar 16, 2024. It is now read-only.

Commit 33b69a8

Browse files
authored
Update documentation to add error handler (#54)
1 parent dc71913 commit 33b69a8

File tree

2 files changed

+59
-14
lines changed

2 files changed

+59
-14
lines changed

documentation/docs/full_example.md

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,19 @@
44
from typing import List, Optional
55

66
import uvicorn
7-
from fastapi import FastAPI, Depends, Query, Body
7+
from fastapi import FastAPI, Depends, Query, Body, Request
8+
from fastapi.responses import JSONResponse
89
from pydantic import SecretStr
910

10-
from fastapi_keycloak import FastAPIKeycloak, OIDCUser, UsernamePassword, HTTPMethod, KeycloakUser, KeycloakGroup
11+
from fastapi_keycloak import (
12+
FastAPIKeycloak,
13+
OIDCUser,
14+
UsernamePassword,
15+
HTTPMethod,
16+
KeycloakUser,
17+
KeycloakGroup,
18+
KeycloakError
19+
)
1120

1221
app = FastAPI()
1322
idp = FastAPIKeycloak(
@@ -21,10 +30,24 @@ idp = FastAPIKeycloak(
2130
idp.add_swagger_config(app)
2231

2332

33+
# Custom error handler for showing Keycloak errors on FastAPI
34+
@app.exception_handler(KeycloakError)
35+
async def keycloak_exception_handler(request: Request, exc: KeycloakError):
36+
return JSONResponse(
37+
status_code=exc.status_code,
38+
content={"message": exc.reason},
39+
)
40+
41+
2442
# Admin
2543

2644
@app.post("/proxy", tags=["admin-cli"])
27-
def proxy_admin_request(relative_path: str, method: HTTPMethod, additional_headers: dict = Body(None), payload: dict = Body(None)):
45+
def proxy_admin_request(
46+
relative_path: str,
47+
method: HTTPMethod,
48+
additional_headers: dict = Body(None),
49+
payload: dict = Body(None),
50+
):
2851
return idp.proxy(
2952
additional_headers=additional_headers,
3053
relative_path=relative_path,
@@ -56,8 +79,17 @@ def get_user_by_query(query: str = None):
5679

5780

5881
@app.post("/users", tags=["user-management"])
59-
def create_user(first_name: str, last_name: str, email: str, password: SecretStr, id: str = None):
60-
return idp.create_user(first_name=first_name, last_name=last_name, username=email, email=email, password=password.get_secret_value(), id=id)
82+
def create_user(
83+
first_name: str, last_name: str, email: str, password: SecretStr, id: str = None
84+
):
85+
return idp.create_user(
86+
first_name=first_name,
87+
last_name=last_name,
88+
username=email,
89+
email=email,
90+
password=password.get_secret_value(),
91+
id=id
92+
)
6193

6294

6395
@app.get("/user/{user_id}", tags=["user-management"])
@@ -182,12 +214,14 @@ def get_current_users_roles(user: OIDCUser = Depends(idp.get_current_user())):
182214

183215
@app.get("/admin", tags=["example-user-request"])
184216
def company_admin(user: OIDCUser = Depends(idp.get_current_user(required_roles=["admin"]))):
185-
return f'Hi admin {user}'
217+
return f"Hi admin {user}"
186218

187219

188-
@app.get("/login", tags=["example-user-request"])
189-
def login(user: UsernamePassword = Depends()):
190-
return idp.user_login(username=user.username, password=user.password.get_secret_value())
220+
@app.post("/login", tags=["example-user-request"])
221+
def login(user: UsernamePassword = Body(...)):
222+
return idp.user_login(
223+
username=user.username, password=user.password.get_secret_value()
224+
)
191225

192226

193227
# Auth Flow
@@ -207,6 +241,6 @@ def logout():
207241
return idp.logout_uri
208242

209243

210-
if __name__ == '__main__':
211-
uvicorn.run('app:app', host="127.0.0.1", port=8081)
244+
if __name__ == "__main__":
245+
uvicorn.run("app:app", host="127.0.0.1", port=8081)
212246
```

tests/app.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
from typing import List, Optional
22

33
import uvicorn
4-
from fastapi import Body, Depends, FastAPI, Query
4+
from fastapi import FastAPI, Depends, Query, Body, Request
5+
from fastapi.responses import JSONResponse
56
from pydantic import SecretStr
67

78
from fastapi_keycloak import (
@@ -10,6 +11,7 @@
1011
KeycloakUser,
1112
OIDCUser,
1213
UsernamePassword,
14+
KeycloakError
1315
)
1416

1517
app = FastAPI()
@@ -25,6 +27,15 @@
2527
idp.add_swagger_config(app)
2628

2729

30+
# Custom error handler for showing Keycloak errors on FastAPI
31+
@app.exception_handler(KeycloakError)
32+
async def keycloak_exception_handler(request: Request, exc: KeycloakError):
33+
return JSONResponse(
34+
status_code=exc.status_code,
35+
content={"message": exc.reason},
36+
)
37+
38+
2839
# Admin
2940

3041

@@ -212,8 +223,8 @@ def company_admin(
212223
return f"Hi admin {user}"
213224

214225

215-
@app.get("/login", tags=["example-user-request"])
216-
def login(user: UsernamePassword = Depends()):
226+
@app.post("/login", tags=["example-user-request"])
227+
def login(user: UsernamePassword = Body(...)):
217228
return idp.user_login(
218229
username=user.username, password=user.password.get_secret_value()
219230
)

0 commit comments

Comments
 (0)