Skip to content

Commit

Permalink
Add SDK frontend client generator
Browse files Browse the repository at this point in the history
  • Loading branch information
asacristani committed Oct 8, 2023
1 parent 3f1579a commit c4daed2
Show file tree
Hide file tree
Showing 8 changed files with 281 additions and 6 deletions.
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,9 @@ __pycache__
.idea

# VENV
venv
venv
node_modules

# GENEREATE SDK CLIENT
src
openapi.json
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
types: [python]
- id: flake8
name: flake8
entry: flake8 --extend-ignore E712
entry: flake8 --extend-ignore E712 --extend-ignore=E203
language: system
types: [python]
exclude: '^app/core/db/migrations/|^app/core/middleware/db_session_context.py$'
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ alembic_downgrade:

format:
black .

generate_sdk:
python sdk_client_script.py
npm run generate-client
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,13 @@
- **Authentication**: OAuth2 with access/refresh tokens.
- **Admin dashboard**: custom admin dashboard as django by sqladmin.
- **Reliable**: CI, integrity testing and covered by unit test at 95%.
- **Frontend friendly**: auto generation of SDK Typescript client.


## ⚙️ Requirements
- [Python 3.11](https://www.python.org/downloads/release/python-3114/)
- [Docker](https://docs.docker.com/engine/install/)
- [Node](https://nodejs.org/en) (only for SDK frontend generation)


## 🎛️ Use
Expand Down Expand Up @@ -97,6 +99,11 @@ ADMIN_USER=superuser
ADMIN_PASS=admin
```

For generating the SDK frontend client (the app should be running):
```shell
make generate_sdk
```

### 🧪 Test
Run pytest with coverage for unit testing.

Expand Down Expand Up @@ -200,7 +207,6 @@ Also, it is possible you want to modify the expiry time of access/refresh tokens
- Relationship of records into model details (performance)

### Others
- TypeScript client
- Deployment with Kubernetes in Google Cloud by Terraform
- Add logging

Expand Down
14 changes: 11 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pika
import redis
from fastapi import FastAPI
from fastapi.routing import APIRoute
from sqladmin import Admin
from sqlalchemy.exc import OperationalError

Expand All @@ -13,7 +14,14 @@
from .services.user.routes import router as user_router
from .settings import settings

app = FastAPI()

# SDK CLIENT GENERATION
def custom_generate_unique_id(route: APIRoute):
"""Modifier of tags for openapi for improving the sdk client experience"""
return f"{route.tags[0]}-{route.name}"


app = FastAPI(generate_unique_id_function=custom_generate_unique_id)

# ROUTERS
routers = [user_router]
Expand All @@ -35,7 +43,7 @@
app.add_middleware(DBSessionMiddleware, custom_engine=get_engine())


@app.get("/")
@app.get("/", tags=["general"])
def read_root():
return {"msg": "Welcome to the backend core in in FastAPI!"}

Expand All @@ -48,7 +56,7 @@ def check_db_connection():
return False


@app.get("/check_health")
@app.get("/check_health", tags=["general"])
async def check_health():
"""
Check all the services in the infrastructure are working
Expand Down
215 changes: 215 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"devDependencies": {
"openapi-typescript-codegen": "^0.25.0"
},
"scripts": {
"generate-client": "openapi --input ./openapi.json --output ./src/client --client axios"
}
}
29 changes: 29 additions & 0 deletions sdk_client_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import json
from pathlib import Path

import requests

url = "http://localhost:8000/openapi.json"
destination_file = "openapi.json"
response = requests.get(url)

if response.status_code == 200:
with open(destination_file, "wb") as file:
file.write(response.content)
else:
raise Exception(
f"Error downloading the file. Response code: {response.status_code}"
)

file_path = Path("./openapi.json")
openapi_content = json.loads(file_path.read_text())

for path_data in openapi_content["paths"].values():
for operation in path_data.values():
tag = operation["tags"][0]
operation_id = operation["operationId"]
to_remove = f"{tag}-"
new_operation_id = operation_id[len(to_remove) :]
operation["operationId"] = new_operation_id

file_path.write_text(json.dumps(openapi_content))

0 comments on commit c4daed2

Please sign in to comment.