Skip to content

3.1 const #896

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

Merged
merged 8 commits into from
Dec 3, 2023
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/preview_release_pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
git config user.email [email protected]
- uses: knope-dev/[email protected]
with:
version: 0.13.0
version: 0.13.2
- run: knope prepare-release --verbose
env:
GITHUB_TOKEN: ${{ secrets.PAT }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release-dry-run.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ jobs:
- name: Install Knope
uses: knope-dev/[email protected]
with:
version: 0.13.0
version: 0.13.2
- run: knope prepare-release --dry-run
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Install Knope
uses: knope-dev/[email protected]
with:
version: 0.13.0
version: 0.13.2
- name: Install Poetry
run: pip install --upgrade poetry
- name: Push to PyPI
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ htmlcov/

# Generated end to end test data
my-test-api-client/
custom-e2e/
custom-e2e/
3-1-features-client
49 changes: 49 additions & 0 deletions end_to_end_tests/3.1_specific.openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
openapi: "3.1.0"
info:
title: "Test 3.1 Features"
description: "Test new OpenAPI 3.1 features"
version: "0.1.0"
paths:
"/const/{path}":
post:
tags: [ "const" ]
parameters:
- in: "path"
required: true
schema:
const: "this goes in the path"
name: "path"
- in: "query"
required: true
schema:
const: "this always goes in the query"
name: "required query"
- in: "query"
schema:
const: "this sometimes goes in the query"
name: "optional query"
requestBody:
required: true
content:
"application/json":
schema:
type: object
properties:
required:
const: "this always goes in the body"
optional:
const: "this sometimes goes in the body"
nullable:
oneOf:
- type: "null"
- const: "this or null goes in the body"
required:
- required
- nullable
responses:
"200":
description: "Successful Response"
content:
"application/json":
schema:
const: "Why have a fixed response? I dunno"
36 changes: 32 additions & 4 deletions end_to_end_tests/regen_golden_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

def regen_golden_record():
runner = CliRunner()
openapi_path = Path(__file__).parent / "openapi_3.0.json"
openapi_path = Path(__file__).parent / "baseline_openapi_3.0.json"

gr_path = Path(__file__).parent / "golden-record"
output_path = Path.cwd() / "my-test-api-client"
Expand All @@ -21,7 +21,28 @@ def regen_golden_record():
shutil.rmtree(gr_path, ignore_errors=True)
shutil.rmtree(output_path, ignore_errors=True)

result = runner.invoke(app, ["generate", f"--config={config_path}", f"--path={openapi_path}"])
result = runner.invoke(
app, ["generate", f"--config={config_path}", f"--path={openapi_path}"]
)

if result.stdout:
print(result.stdout)
if result.exception:
raise result.exception
output_path.rename(gr_path)


def regen_golden_record_3_1_features():
runner = CliRunner()
openapi_path = Path(__file__).parent / "3.1_specific.openapi.yaml"

gr_path = Path(__file__).parent / "test-3-1-golden-record"
output_path = Path.cwd() / "test-3-1-features-client"

shutil.rmtree(gr_path, ignore_errors=True)
shutil.rmtree(output_path, ignore_errors=True)

result = runner.invoke(app, ["generate", f"--path={openapi_path}"])

if result.stdout:
print(result.stdout)
Expand All @@ -32,7 +53,7 @@ def regen_golden_record():

def regen_custom_template_golden_record():
runner = CliRunner()
openapi_path = Path(__file__).parent / "openapi_3.0.json"
openapi_path = Path(__file__).parent / "baseline_openapi_3.0.json"
tpl_dir = Path(__file__).parent / "test_custom_templates"

gr_path = Path(__file__).parent / "golden-record"
Expand All @@ -45,7 +66,13 @@ def regen_custom_template_golden_record():

os.chdir(str(output_path.absolute()))
result = runner.invoke(
app, ["generate", f"--config={config_path}", f"--path={openapi_path}", f"--custom-template-path={tpl_dir}"]
app,
[
"generate",
f"--config={config_path}",
f"--path={openapi_path}",
f"--custom-template-path={tpl_dir}",
],
)

if result.stdout:
Expand Down Expand Up @@ -76,4 +103,5 @@ def regen_custom_template_golden_record():

if __name__ == "__main__":
regen_golden_record()
regen_golden_record_3_1_features()
regen_custom_template_golden_record()
23 changes: 23 additions & 0 deletions end_to_end_tests/test-3-1-golden-record/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
__pycache__/
build/
dist/
*.egg-info/
.pytest_cache/

# pyenv
.python-version

# Environments
.env
.venv

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# JetBrains
.idea/

/coverage.xml
/.coverage
124 changes: 124 additions & 0 deletions end_to_end_tests/test-3-1-golden-record/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# test-3-1-features-client
A client library for accessing Test 3.1 Features

## Usage
First, create a client:

```python
from test_3_1_features_client import Client

client = Client(base_url="https://api.example.com")
```

If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead:

```python
from test_3_1_features_client import AuthenticatedClient

client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken")
```

Now call your endpoint and use your models:

```python
from test_3_1_features_client.models import MyDataModel
from test_3_1_features_client.api.my_tag import get_my_data_model
from test_3_1_features_client.types import Response

with client as client:
my_data: MyDataModel = get_my_data_model.sync(client=client)
# or if you need more info (e.g. status_code)
response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)
```

Or do the same thing with an async version:

```python
from test_3_1_features_client.models import MyDataModel
from test_3_1_features_client.api.my_tag import get_my_data_model
from test_3_1_features_client.types import Response

async with client as client:
my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)
```

By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle.

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl="/path/to/certificate_bundle.pem",
)
```

You can also disable certificate validation altogether, but beware that **this is a security risk**.

```python
client = AuthenticatedClient(
base_url="https://internal_api.example.com",
token="SuperSecretToken",
verify_ssl=False
)
```

Things to know:
1. Every path/method combo becomes a Python module with four functions:
1. `sync`: Blocking request that returns parsed data (if successful) or `None`
1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful.
1. `asyncio`: Like `sync` but async instead of blocking
1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking

1. All path/query params, and bodies become method arguments.
1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above)
1. Any endpoint which did not have a tag will be in `test_3_1_features_client.api.default`

## Advanced customizations

There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case):

```python
from test_3_1_features_client import Client

def log_request(request):
print(f"Request event hook: {request.method} {request.url} - Waiting for response")

def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")

client = Client(
base_url="https://api.example.com",
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)

# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()
```

You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url):

```python
import httpx
from test_3_1_features_client import Client

client = Client(
base_url="https://api.example.com",
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030"))
```

## Building / publishing this package
This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics:
1. Update the metadata in pyproject.toml (e.g. authors, version)
1. If you're using a private repository, configure it with Poetry
1. `poetry config repositories.<your-repository-name> <url-to-your-repository>`
1. `poetry config http-basic.<your-repository-name> <username> <password>`
1. Publish the client with `poetry publish --build -r <your-repository-name>` or, if for public PyPI, just `poetry publish --build`

If you want to install this client into another project without publishing it (e.g. for development) then:
1. If that project **is using Poetry**, you can simply do `poetry add <path-to-this-client>` from that project
1. If that project is not using Poetry:
1. Build a wheel with `poetry build -f wheel`
1. Install that wheel from the other project `pip install <path-to-wheel>`
26 changes: 26 additions & 0 deletions end_to_end_tests/test-3-1-golden-record/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[tool.poetry]
name = "test-3-1-features-client"
version = "0.1.0"
description = "A client library for accessing Test 3.1 Features"

authors = []

readme = "README.md"
packages = [
{include = "test_3_1_features_client"},
]
include = ["CHANGELOG.md", "test_3_1_features_client/py.typed"]

[tool.poetry.dependencies]
python = "^3.8"
httpx = ">=0.20.0,<0.26.0"
attrs = ">=21.3.0"
python-dateutil = "^2.8.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.ruff]
select = ["F", "I"]
line-length = 120
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
""" A client library for accessing Test 3.1 Features """
from .client import AuthenticatedClient, Client

__all__ = (
"AuthenticatedClient",
"Client",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
""" Contains methods for accessing the API """
Loading