Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for dependencies in routes and support Python 3.12 #44

Merged
merged 9 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11"]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
steps:
- name: Checkout 🔁
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1
Expand Down
11 changes: 6 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v4.6.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
Expand All @@ -21,24 +21,25 @@ repos:
args: ["--fix=crlf"]
files: \.bat$
- repo: https://github.com/pycqa/isort
rev: 5.12.0
rev: 5.13.2
hooks:
- id: isort
language_version: python3
- repo: https://github.com/psf/black
rev: 23.11.0
rev: 24.4.2
hooks:
- id: black
language_version: python3
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.1.0
hooks:
- id: prettier
exclude: "^openapi_to_fastapi/tests/__snapshots__/"
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
rev: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/twu/skjold
rev: v0.6.1
rev: v0.6.2
hooks:
- id: skjold
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ router = SpecRouter(specs, validators=[MyValidator])

You will need:

- Python 3.8+ (though 3.11+ might have some issues with dependencies)
- Python 3.8.1+ (tested on 3.8 - 3.12)
- [pre-commit](https://pre-commit.com/#install)

Before working on the project, make sure you run:
Expand Down
4 changes: 0 additions & 4 deletions openapi_to_fastapi/model_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ def generate_model_from_schema(schema: str, format_code: bool = False) -> str:
extra_template_data=None,
target_python_version=PythonVersion.PY_38,
dump_resolve_reference_action=None,
# Validation of OpenAPI 3.1 specs isn't supported right now. Issues:
# https://github.com/koxudaxi/datamodel-code-generator/issues/1649 and
# https://github.com/RonnyPfannschmidt/prance/issues/95
validation=False,
field_constraints=False,
snake_case_field=False,
strip_default_none=False,
Expand Down
9 changes: 7 additions & 2 deletions openapi_to_fastapi/routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Type, Union
from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union

import pydantic
from fastapi import APIRouter
from fastapi import APIRouter, params
from fastapi.openapi import models as oas

from .model_generator import load_models
Expand Down Expand Up @@ -35,6 +35,7 @@ class RouteInfo:
tags: Optional[List[str]] = None
summary: Optional[str] = None
deprecated: Optional[bool] = None
dependencies: Optional[Sequence[params.Depends]] = None

request_model: Optional[Type[pydantic.BaseModel]] = None
response_model: Optional[Type[pydantic.BaseModel]] = None
Expand Down Expand Up @@ -188,6 +189,7 @@ def post(
response_description: Optional[str] = None,
name_factory: Optional[Callable] = None,
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
dependencies: Optional[Sequence[params.Depends]] = None,
):
"""
Define implementation for a specific POST route
Expand All @@ -201,6 +203,7 @@ def post(
:param description: Route description. Got from OpenAPI spec by default
:param response_description: Description of the response
:param responses: Possible responses the route may return. Used in documentation
:param dependencies: Possible dependencies to add to the route.
"""

def _wrapper(fn):
Expand All @@ -215,6 +218,7 @@ def _wrapper(fn):
route_info.tags = tags
route_info.name_factory = name_factory
route_info.responses = responses
route_info.dependencies = dependencies

if response_description:
route_info.response_description = response_description
Expand Down Expand Up @@ -258,5 +262,6 @@ def to_fastapi_router(self):
responses=route_info.responses,
tags=route_info.tags,
deprecated=route_info.deprecated,
dependencies=route_info.dependencies,
)(handler)
return router
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"detail": [
{
"input": null,
"loc": [
"query",
"vendor"
],
"msg": "Field required",
"type": "missing"
},
{
"input": null,
"loc": [
"header",
"auth-header"
],
"msg": "Field required",
"type": "missing"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"detail": [
{
"input": "1,1.2",
"loc": [
"body",
"lat"
],
"msg": "Input should be a valid number, unable to parse string as a number",
"type": "float_parsing"
},
{
"ctx": {
"le": 180.0
},
"input": "99999",
"loc": [
"body",
"lon"
],
"msg": "Input should be less than or equal to 180",
"type": "less_than_equal"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"detail": [
{
"input": {},
"loc": [
"body",
"lat"
],
"msg": "Field required",
"type": "missing"
},
{
"input": {},
"loc": [
"body",
"lon"
],
"msg": "Field required",
"type": "missing"
}
]
}
6 changes: 6 additions & 0 deletions openapi_to_fastapi/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
from syrupy.extensions.json import JSONSnapshotExtension

from openapi_to_fastapi.routes import SpecRouter

Expand All @@ -28,3 +29,8 @@ def definitions_client(specs_root):
spec_router = SpecRouter(specs_root / "definitions")
app.include_router(spec_router.to_fastapi_router())
return TestClient(app)


@pytest.fixture
def json_snapshot(snapshot):
return snapshot.use_extension(JSONSnapshotExtension)
Empty file.
65 changes: 0 additions & 65 deletions openapi_to_fastapi/tests/snapshots/snap_test_router.py

This file was deleted.

50 changes: 42 additions & 8 deletions openapi_to_fastapi/tests/test_router.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import pydantic
import pytest
from fastapi import Header
from fastapi import Depends, Header, HTTPException, Request
from pydantic import BaseModel
from starlette.status import HTTP_418_IM_A_TEAPOT

from openapi_to_fastapi.model_generator import load_models
from openapi_to_fastapi.routes import SpecRouter
Expand Down Expand Up @@ -44,7 +45,7 @@ def test_pydantic_model_loading(specs_root):
assert module.ValidationError(loc=[], msg="Crap", type="Error")


def test_weather_route_payload_errors(app, specs_root, client, snapshot):
def test_weather_route_payload_errors(app, specs_root, client, json_snapshot):
spec_router = SpecRouter(specs_root / "definitions")

@spec_router.post("/Weather/Current/Metric")
Expand All @@ -55,14 +56,14 @@ def weather_metric(request):

resp = client.post("/Weather/Current/Metric", json={})
assert resp.status_code == 422
snapshot.assert_match(resp.json(), "Missing payload")
assert json_snapshot == resp.json(), "Missing payload"

resp = client.post("/Weather/Current/Metric", json={"lat": "1,1.2", "lon": "99999"})
assert resp.status_code == 422
snapshot.assert_match(resp.json(), "Incorrect payload type")
assert json_snapshot == resp.json(), "Incorrect payload type"


def test_company_custom_post_route(app, client, specs_root, snapshot):
def test_company_custom_post_route(app, client, specs_root):
spec_router = SpecRouter(specs_root / "definitions")

@spec_router.post("/Company/BasicInfo")
Expand All @@ -76,7 +77,7 @@ def weather_metric(request):
assert resp.json() == company_basic_info_resp


def test_default_post_handler(app, client, specs_root, snapshot):
def test_default_post_handler(app, client, specs_root):
spec_router = SpecRouter(specs_root / "definitions")

@spec_router.post()
Expand All @@ -89,7 +90,7 @@ def company_info(request):
assert resp.json() == company_basic_info_resp


def test_custom_route_definitions(app, client, specs_root, snapshot):
def test_custom_route_definitions(app, client, specs_root, json_snapshot):
spec_router = SpecRouter(specs_root / "definitions")

@spec_router.post("/Weather/Current/Metric")
Expand All @@ -99,7 +100,7 @@ def weather_metric(request, vendor: str, auth_header: str = Header(...)):
app.include_router(spec_router.to_fastapi_router())
resp = client.post("/Weather/Current/Metric", json={"lat": "30.5", "lon": 1.56})
assert resp.status_code == 422
snapshot.assert_match(resp.json(), "Custom route definition")
assert json_snapshot == resp.json(), "Custom route definition"


def test_response_model_is_parsed(app, client, specs_root):
Expand Down Expand Up @@ -251,3 +252,36 @@ def test_custom_responses(app, specs_root):
assert issubclass(model, BaseModel)
assert "ok" in model.model_fields
assert "errorMessage" in model.model_fields


def test_dependencies(app, client, specs_root):
async def teapot_dependency(request: Request):
"""
Dependency used just for testing.
"""
if request.headers.get("X-Brew") != "tea":
raise HTTPException(
HTTP_418_IM_A_TEAPOT,
"I'm a teapot",
)

spec_router = SpecRouter(specs_root / "definitions")

@spec_router.post("/Company/BasicInfo", dependencies=[Depends(teapot_dependency)])
def weather_metric(request):
return company_basic_info_resp

app.include_router(spec_router.to_fastapi_router())

# Normal request, not affected by the dependency
resp = client.post(
"/Company/BasicInfo", json={"companyId": "test"}, headers={"X-Brew": "tea"}
)
assert resp.status_code == 200, resp.json()
assert resp.json() == company_basic_info_resp

# Custom request, affected by the dependency
resp = client.post(
"/Company/BasicInfo", json={"companyId": "test"}, headers={"X-Brew": "coffee"}
)
assert resp.status_code == 418, resp.json()
Loading
Loading