Generate modern Python clients from OpenAPI

Overview

Run Checks codecov MIT license Generic badge Code style: black PyPI version shields.io Downloads

openapi-python-client

Generate modern Python clients from OpenAPI 3.x documents.

This generator does not support OpenAPI 2.x FKA Swagger. If you need to use an older document, try upgrading it to version 3 first with one of many available converters.

This project is still in development and does not support all OpenAPI features

Why This?

This tool focuses on creating the best developer experience for Python developers by:

  1. Using all the latest and greatest Python features like type annotations and dataclasses.
  2. Having documentation and usage instructions specific to this one generator.
  3. Being written in Python with Jinja2 templates, making it easier to improve and extend for Python developers. It's also much easier to install and use if you already have Python.

Installation

I recommend you install with pipx so you don't conflict with any other packages you might have: pipx install openapi-python-client --include-deps.

Note the --include-deps option which will also make black, isort, and autoflake available in your path so that openapi-python-client can use them to clean up the generated code.

If you use pipx run then the post-generation hooks will not be available unless you install them manually.

You can also install with normal pip: pip install openapi-python-client

Then, if you want tab completion: openapi-python-client --install-completion

Usage

Create a new client

openapi-python-client generate --url https://my.api.com/openapi.json

This will generate a new client library named based on the title in your OpenAPI spec. For example, if the title of your API is "My API", the expected output will be "my-api-client". If a folder already exists by that name, you'll get an error.

If you have an openapi.json file available on disk, in any CLI invocation you can build off that instead by replacing --url with a --path:

openapi-python-client generate --path location/on/disk/openapi.json

Update an existing client

openapi-python-client update --url https://my.api.com/openapi.json

For more usage details run openapi-python-client --help or read usage

Using custom templates

This feature leverages Jinja2's ChoiceLoader and FileSystemLoader. This means you do not need to customize every template. Simply copy the template(s) you want to customize from the default template directory to your own custom template directory (file names must match exactly) and pass the template directory through the custom-template-path flag to the generate and update commands. For instance,

openapi-python-client update \
  --url https://my.api.com/openapi.json \
  --custom-template-path=relative/path/to/mytemplates

Be forewarned, this is a beta-level feature in the sense that the API exposed in the templates is undocumented and unstable.

What You Get

  1. A pyproject.toml file with some basic metadata intended to be used with Poetry.
  2. A README.md you'll most definitely need to update with your project's details
  3. A Python module named just like the auto-generated project name (e.g. "my_api_client") which contains:
    1. A client module which will have both a Client class and an AuthenticatedClient class. You'll need these for calling the functions in the api module.
    2. An api module which will contain one module for each tag in your OpenAPI spec, as well as a default module for endpoints without a tag. Each of these modules in turn contains one function for calling each endpoint.
    3. A models module which has all the classes defined by the various schemas in your OpenAPI spec

For a full example you can look at the end_to_end_tests directory which has an openapi.json file. "golden-record" in that same directory is the generated client from that OpenAPI document.

OpenAPI features supported

  1. All HTTP Methods
  2. JSON and form bodies, path and query parameters
  3. File uploads with multipart/form-data bodies
  4. float, string, int, date, datetime, string enums, and custom schemas or lists containing any of those
  5. html/text or application/json responses containing any of the previous types
  6. Bearer token security

Configuration

You can pass a YAML (or JSON) file to openapi-python-client with the --config option in order to change some behavior. The following parameters are supported:

class_overrides

Used to change the name of generated model classes. This param should be a mapping of existing class name (usually a key in the "schemas" section of your OpenAPI document) to class_name and module_name. As an example, if the name of the a model in OpenAPI (and therefore the generated class name) was something like "_PrivateInternalLongName" and you want the generated client's model to be called "ShortName" in a module called "short_name" you could do this:

Example:

class_overrides:
  _PrivateInternalLongName:
    class_name: ShortName
    module_name: short_name

The easiest way to find what needs to be overridden is probably to generate your client and go look at everything in the models folder.

project_name_override and package_name_override

Used to change the name of generated client library project/package. If the project name is changed but an override for the package name isn't provided, the package name will be converted from the project name using the standard convention (replacing -'s with _'s).

Example:

project_name_override: my-special-project-name
package_name_override: my_extra_special_package_name

field_prefix

When generating properties, the name attribute of the OpenAPI schema will be used. When the name is not a valid Python identifier (e.g. begins with a number) this string will be prepended. Defaults to "field_".

Example:

field_prefix: attr_

package_version_override

Specify the package version of the generated client. If unset, the client will use the version of the OpenAPI spec.

Example:

package_version_override: 1.2.3

post_hooks

In the config file, there's an easy way to tell openapi-python-client to run additional commands after generation. Here's an example showing the default commands that will run if you don't override them in config:

post_hooks:
   - "autoflake -i -r --remove-all-unused-imports --remove-unused-variables --ignore-init-module-imports ."
   - "isort ."
   - "black ."
Comments
  • Add support for recursively defined schemas

    Add support for recursively defined schemas

    Describe the bug I tried to create a python client from an OpenApi-Spec with the command openapi-python-client generate --path secret_server_openapi3.json. Then I got multple warnings:

    • invalid data in items of array settings
    • Could not find reference in parsed models or enums
    • Cannot parse response for status code 200, response will be ommitted from generated client I searched the schemas, which are responsible for the errors and they all had in common, that they either reference another schema which is recursively defined or reference themself. For example one of the problematic schemas:
    {
      "SecretDependencySetting": {
            "type": "object",
            "properties": {
              "active": {
                "type": "boolean",
                "description": "Indicates the setting is active."
              },
              "childSettings": {
                "type": "array",
                "description": "The Child Settings that would be used  for list of options.",
                "items": {
                  "$ref": "#/components/schemas/SecretDependencySetting"
                }
              }
            },
            "description": "Secret Dependency Settings - Mostly used internally"
          }
    }
    

    To Reproduce Define a schema recursively and then try to create a client from it.

    Expected behavior The software can also parse a recursively defined schema.

    OpenAPI Spec File It's 66000 Lines, so I'm not sure if this will help you, or github will allow me to post it :smile: Just ask if you need specific parts of the spec, aside from what I already provided above.

    Desktop (please complete the following information):

    • OS: Linux Manjaro
    • Python Version: 3.9.1
    • openapi-python-client version 0.7.3
    enhancement here there be dragons 
    opened by sp-schoen 13
  • Use `Any` for schemas with no `type`

    Use `Any` for schemas with no `type`

    Describe the bug When there's a model property with no type field, it causes a NoneProperty to be generated. I believe that according to JSONSchema, if there is no type specified, it should accept any type (though I'm not 100% sure; see conflicting answers in this thread https://stackoverflow.com/questions/29230349/is-type-optional-in-json-schema). It does seem more logical to compile to Any rather than None, since there's already type: null in JSONSchema.

    To Reproduce Add a model with a property with no type, such as:

        Field:
          type: object
          properties:
            value:
    		  description: Field value
    

    Expected behavior Expected the generated field.py model to have value: Any.

    OpenAPI Spec File See above

    Desktop (please complete the following information):

    • OS: [e.g. macOS 10.15.1]
    • Python Version: [e.g. 3.8.0]
    • openapi-python-client version [e.g. 0.1.0]
    enhancement 
    opened by forest-benchling 12
  • Don't depend on stringcase (closes #369)

    Don't depend on stringcase (closes #369)

    Let's reimplement what we need here so that we don't depend on stringcase anymore (see #369 for rationale). I've added a few test cases for stuff I've seen break along the way.

    opened by ramnes 12
  • Prefer property name instead of title for class name

    Prefer property name instead of title for class name

    When the title of a schema object doesn't match its property name, reference resolution breaks. Simplest demonstration:

    #!/usr/bin/env python3
    from typing import Generic, TypeVar
    from pydantic import BaseModel
    from pydantic.generics import GenericModel
    from fastapi import FastAPI
    
    app = FastAPI()
    
    T = TypeVar('T')
    
    class GenericItem(GenericModel, Generic[T]):
        prop: T
    
    @app.get("/int_item", response_model=GenericItem[int])
    def get_int_item():
        return GenericItem[int](prop=88)
    

    This will cause the client to produce a warning:

    Warning(s) encountered while generating. Client was generated, but some pieces may be missing
    
    WARNING parsing GET /int_item within default.
    
    Cannot parse response for status code 200, response will be ommitted from generated client
    
    Reference(ref='#/components/schemas/GenericItem_int_')
    

    This pull request fixes this by prefering the property name as the class name for a model over its title.

    opened by jrversteegh 12
  • Support non-schema components and references (e.g. parameters)

    Support non-schema components and references (e.g. parameters)

    Describe the bug When building the client with the path parameter in the yaml file which are passed through reference, it does not consider the parameter and the generated client does not have those referenced parameters.

    To Reproduce Steps to reproduce the behavior:

    1. Take any open api sample yaml file that have path parameters in it.
    2. Pass that parameter as reference like for example, parameters: - $ref: '#/components/parameters/sampleparam'
    3. Generate client using command "openapi-python-client generate --path <yaml_path>"

    Expected behavior It should consider the path parameters passed through reference too same as the parameters that it considers when passed with the standard way.

    OpenAPI Spec File Any openapi spec file could be used.

    Desktop (please complete the following information):

    • OS: macOS 10.15.6
    • Python Version: 3.7.3
    • openapi-python-client 0.7.3

    Additional context It does not raise any error while building the client, but it does not have the referenced parameters in the generated client.

    enhancement 
    opened by Aniketghumed 12
  • Support of recursive and circular references

    Support of recursive and circular references

    Is your feature request related to a problem? Please describe. References to schemas that have not been processed yet are not supported now. See the example.

    Describe the solution you'd like I suggest to add models that are referenced without properties. And fill in the properties later. This adds the ability to refer to schemas that have not been processed yet.

    Describe alternatives you've considered Also it may also be easier to create all models without properties first, then add properties with second pass.

    Additional context Example OpenAPI:

    openapi: 3.0.3
    info:
      title: 'Example'
      version: 0.1.0
    servers:
      - url: 'http://example.com'
    paths:
      '/foo':
        delete:
          responses:
            '200':
              description: OK
    components:
      schemas:
        Brother:
          type: object
          properties:
            sister:
              $ref: '#/components/schemas/Sister'
        Sister:
          type: object
          properties:
            brother:
              $ref: '#/components/schemas/Brother'
    

    Generator produces warnings and models package is empty.

    Could not find reference in parsed models or enums
    Reference(ref='#/components/schemas/Sister')
    
    Could not find reference in parsed models or enums
    Reference(ref='#/components/schemas/Brother')
    

    I expect the generated models for Brother and Sister. Something like:

    # models/brother.py
    class Brother:
        sister: Union[Unset, Sister] = UNSET
    
    # models/sister.py
    class Sister:
        brother: Union[Unset, Brother] = UNSET
    
    enhancement here there be dragons 
    opened by mtovts 11
  • Exception when generating list properties in multipart forms

    Exception when generating list properties in multipart forms

    After upgrading from 0.9.2 to 0.10.0 the client generation fails with:

    Traceback (most recent call last):
      File "REDACTED/.venv/bin/openapi-python-client", line 8, in <module>
        sys.exit(app())
      File "REDACTED/.venv/lib/python3.8/site-packages/typer/main.py", line 214, in __call__
        return get_command(self)(*args, **kwargs)
      File "REDACTED/.venv/lib/python3.8/site-packages/click/core.py", line 829, in __call__
        return self.main(*args, **kwargs)
      File "REDACTED/.venv/lib/python3.8/site-packages/click/core.py", line 782, in main
        rv = self.invoke(ctx)
      File "REDACTED/.venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "REDACTED/.venv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
        return ctx.invoke(self.callback, **ctx.params)
      File "REDACTED/.venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
        return callback(*args, **kwargs)
      File "REDACTED/.venv/lib/python3.8/site-packages/typer/main.py", line 497, in wrapper
        return callback(**use_params)  # type: ignore
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/cli.py", line 141, in generate
        errors = create_new_client(
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/__init__.py", line 314, in create_new_client
        return project.build()
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/__init__.py", line 108, in build
        self._build_api()
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/__init__.py", line 263, in _build_api
        module_path.write_text(endpoint_template.render(endpoint=endpoint), encoding=self.file_encoding)
      File "REDACTED/.venv/lib/python3.8/site-packages/jinja2/environment.py", line 1289, in render
        self.environment.handle_exception()
      File "REDACTED/.venv/lib/python3.8/site-packages/jinja2/environment.py", line 924, in handle_exception
        raise rewrite_traceback_stack(source=source)
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/templates/endpoint_module.py.jinja", line 38, in top-level template code
        {{ multipart_body(endpoint) | indent(4) }}
      File "REDACTED/.venv/lib/python3.8/site-packages/jinja2/runtime.py", line 828, in _invoke
        rv = self._func(*arguments)
      File "REDACTED/.venv/lib/python3.8/site-packages/openapi_python_client/templates/endpoint_macros.py.jinja", line 80, in template
        {{ transform_multipart(property, property.python_name, destination) }}
      File "REDACTED/.venv/lib/python3.8/site-packages/jinja2/utils.py", line 81, in from_obj
        if hasattr(obj, "jinja_pass_arg"):
    jinja2.exceptions.UndefinedError: the template 'property_templates/list_property.py.jinja' (imported on line 79 in 'endpoint_macros.py.jinja') does not export the requested name 'transform_multipart'
    
    bug 
    opened by dpursehouse 11
  • fix: support json and yaml with separate decoding

    fix: support json and yaml with separate decoding

    Fix: #488

    json is not exactly a subset of yaml, as yaml do not support tabs there are maybe other subtleties, so we just use content-type to figure out how to parse

    First commit actually fix the wrong part of the code 🤦 , but it might still be worth to have it behave similarly.

    For a few lines of code, I am not sure it is really worth to factorize, so I didn't bother

    opened by tardyp 10
  • Feature/add-properties-local-reference-support

    Feature/add-properties-local-reference-support

    Title

    Feature/add-properties-local-reference-support

    Description

    This PR aims to bring support of properties local references resolution. It could happen that in a Document a local reference is pointing to one or multiple other virtual references instead to its property definition, as for exemple:

    (...)
        ModelWithAnyJsonProperties:
          title: ModelWithAnyJsonProperties
          type: object
          additionalProperties:
            anyOf:
            - type: object
              additionalProperties:
                type: string
            - type: array
              items:
                type: string
            - type: string
            - type: number
            - type: integer
            - type: boolean
        ModelLocalReferenceLoop:
          "$ref": "#/components/schemas/ModelWithAnyJsonProperties"
        ModelDeeperLocalReferenceLoop:
          "$ref": "#/components/schemas/ModelLocalReferenceLoop"
     (...)
    

    During properties parsing, those virtual reference are resolved by making them pointing to their target ModelProperty or EnumProperty definition.

    Thus, only the target model will be generated and any path referencing them (the virtual reference) will use the target model.

    Also add support for inner property direct and indirect reference to its parent model resolution, as:

    (...)
    AModel:
      title: AModel
      type: object
      properties:
        direct_ref_to_itself:
          $ref: '#/components/schemas/AModel'
        indirect_ref_to_itself:
          $ref: '#/components/schemas/AModelDeeperIndirectReference'
    AModelIndirectReference:
      $ref: '#/components/schemas/AModel'
    AModelDeeperIndirectReference:
      $ref: '#/components/schemas/AModelIndirectReference'
    (...)
    

    QA Notes & Product impact

    Add support for properties local reference ($ref) resolution Add support for inner property direct and indirect reference to its parent model resolution.

    @dbanty

    opened by p1-ra 9
  • feat: Add allOf support for model definitions (#98)

    feat: Add allOf support for model definitions (#98)

    @bowenwr I attempted to implement what I was talking about in my review of #312 . I just cloned that branch and made the changes, so in theory they are based on top of your existing work and could be backported to your fork? Let me know if there's a problem with this implementation or you disagree that it's simpler.

    opened by dbanty 9
  • Use Optional for Query Params Instead of Union[Unset, ...]

    Use Optional for Query Params Instead of Union[Unset, ...]

    Is your feature request related to a problem? Please describe.

    Although I'd like to keep Unset for body params, it makes a lot less sense for query params. I'd like non-required query params to return to the use of Optional.

    While it would be inconsistent with the way we handle body params, I like that it encapsulates Unset (which is something of a workaround) more tightly.

    Describe the solution you'd like

    Given:

    '/things':
        get:
          tags:
          - things
          operationId: getThings
          parameters:
          - name: size
            in: query
            schema:
              type: int
    

    I'd like the signature to look like:

    def sync_detailed(
        *,
        client: Client,
        size: Optional[int] = None,
    ) -> Response[Thing]:
    

    Instead of:

    def sync_detailed(
        *,
        client: Client,
        size: Union[Unset, int] = UNSET,
    ) -> Response[Thing]:
    

    Describe alternatives you've considered

    We have several endpoints with a large number of optional query params that default to None in the wrapping interface. Will probably just iterate the dict and assign Unset everywhere we have None now.

    Additional context

    I feel like I did this to myself having requested the original Unset feature. 😅

    enhancement 
    opened by bowenwr 9
  • chore(deps): update dependency importlib_metadata to v6

    chore(deps): update dependency importlib_metadata to v6

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | importlib_metadata | >2,<6 -> >2,<7 | age | adoption | passing | confidence |


    Release Notes

    python/importlib_metadata

    v6.0.0

    Compare Source

    ======

    • #​419: Declared Distribution as an abstract class, enforcing definition of abstract methods in instantiated subclasses. It's no longer possible to instantiate a Distribution or any subclasses unless they define the abstract methods.

      Please comment in the issue if this change breaks any projects. This change will likely be rolled back if it causes significant disruption.


    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 1
  • Support multi-file schemas

    Support multi-file schemas

    Hello, I'm new to OpenAPI and Schemas world so it could be possible that I'm doing something wrong. I'm trying to add '#ref' to components in openapi.json to link to another file.

    for example: "components": { "schemas": { "User": { "$ref": "./schemas/User" } }

    And I'm getting the errors: Remote references such as ././.. are not supported yet. and Reference schemas are not supported.

    Can I link schemas files some other way? I dont want to write all my schemas in the openapi.json file. Thanks in advance the thank you for this project.

    enhancement 
    opened by axshani 1
  • Tell mypy et.al that Unset is always falsy

    Tell mypy et.al that Unset is always falsy

    Is your feature request related to a problem? Please describe.

    mypy doesn't understand that Unset is always falsy

    if api_object.neighbours:
        for x in api_object.neighbours:  # <-- mypy: error: Item "Unset" of "Union[Unset, None, List[Neighbour]]" has no attribute "__iter__" (not iterable)  [union-attr]
            do_something_with(x)
    

    Describe the solution you'd like

    I would like mypy to understand this automatically

    Type annotation on Unset.__bool__() could be Literal[False] instead of bool, but typing.Literal is not available for python < 3.8.

    enhancement 
    opened by taasan 0
  • fix: Treat leading underscore as a sign of invalid identifier

    fix: Treat leading underscore as a sign of invalid identifier

    There are 2 reasons for this change:

    • leading underscores have special meaning and therefore we should prefix those properties to avoid unexpected semantics
    • in my particular use case my team is working with a schema which has the following fields in an object: "field" and "_field" and current code strips leading underscore and produces invalid data object with 2 fields of the same name
    enhancement breaking 
    opened by maxkomarychev 3
  • OpenAPI with `$ref` responseBodies don't get processed correctly

    OpenAPI with `$ref` responseBodies don't get processed correctly

    Describe the bug A clear and concise description of what the bug is.

    To Reproduce Steps to reproduce the behavior:

    1. Go to '...'
    2. Click on '....'
    3. Scroll down to '....'
    4. See error

    Expected behavior A clear and concise description of what you expected to happen.

    OpenAPI Spec File A link to your openapi.json which produces this issue.

    Desktop (please complete the following information):

    • OS: [e.g. macOS 10.15.1]
    • Python Version: [e.g. 3.8.0]
    • openapi-python-client version [e.g. 0.1.0]

    Additional context Add any other context about the problem here.

    bug 
    opened by tsweeney-dust 1
Releases(v0.12.3)
  • v0.12.3(Dec 18, 2022)

    0.12.3

    Features

    • Add raise_on_unexpected_status flag to generated Client [#593]. Thanks @JamesHinshelwood, @ramnes, @gwenshap, @theFong!
    • add use_path_prefixes_for_title_model_names config option for simpler model names [#559, #560]. Thanks @rtaycher!
    • Support any content type ending in +json [#706, #709]. Thanks @XioNoX and @mtovt!
    Source code(tar.gz)
    Source code(zip)
  • v0.12.2(Dec 4, 2022)

  • v0.12.1(Nov 12, 2022)

  • v0.12.0(Nov 12, 2022)

    0.12.0

    Breaking Changes

    • Change the Response.status_code type to the HTTPStatus enum [#665]

    Features

    • Add endpoint_collections_by_tag and openapi to the templating globals [#689]. Thanks @paulo-raca!
    • Support for recursive and circular references using lazy imports [#670, #338, #466]. Thanks @maz808 & @mtovt!
    • Include __all__ in generated __init__.py files [#676, #631, #540, #675]. Thanks @EltonChou!

    Fixes

    • If data.type is None but has data.properties, assume type is object [#691, #674]. Thanks @ahuang11!
    Source code(tar.gz)
    Source code(zip)
  • v0.11.6(Aug 27, 2022)

    0.11.6

    Features

    • improve the error message when parsing a response fails [#659]. Thanks @supermihi!
    • Authorization header can now be customized in AuthenticatedClient [#660]. Thanks @supermihi!
    • Support inlined form data schema in requestBody [#656, #662]. Thanks @supermihi!
    • Allow enums in headers [#663, #667]. Thanks @supermihi!

    Fixes

    • Exception when parsing documents which contain callbacks [#661]. Thanks @dachucky!
    Source code(tar.gz)
    Source code(zip)
  • v0.11.5(Aug 13, 2022)

    0.11.5

    Features

    • support #/components/parameters references [#288, #615, #653]. Thanks @jsanchez7SC!

    Fixes

    • Keep trailing newlines in generated files [#646, #654]. Thanks @eliask!
    Source code(tar.gz)
    Source code(zip)
  • v0.11.4(Jul 3, 2022)

    0.11.4

    Fixes

    • Invalid code generation with some oneOf and anyOf combinations [#603, #642]. Thanks @jselig-rigetti!
    • Allow relative references in all URLs [#630]. Thanks @jtv8!
    Source code(tar.gz)
    Source code(zip)
  • v.0.11.3(Jun 10, 2022)

  • v.0.11.2(Jun 3, 2022)

  • v.0.11.1(Jan 29, 2022)

    Features

    • Allow httpx 0.22.* in generated clients [#577]

    Fixes

    • Type annotations for optional dates and datetimes in multipart/form [#580]
    • Error generating clients with dates or datetimes in multipart/form [#579]. Thanks @lsaavedr!
    • Include nested packages in generated setup.py [#575, #576]. Thanks @tedo-benchling!
    Source code(tar.gz)
    Source code(zip)
  • v.0.11.0(Jan 19, 2022)

    Breaking Changes

    • Minimum required attrs version in generated clients is now 21.3.0.
    • Python 3.6 is officially not supported. The minimum version has been updated to reflect this.
    • Validation of OpenAPI documents is now more strict.
    • Model names generated from OpenAPI names with periods (.) in them will be different.
    • Header values will be explicitly transformed or omitted instead of blindly passed to httpx as-is.
    • datetime is now considered a reserved word everywhere, so any properties which were named datetime will now be named datetime_.
    • File uploads can now only accept binary payloads (BinaryIO).

    Features

    • Don't set a cap on allowed attrs version.
    • use poetry-core as build backend in generated clients [#565]. Thanks @fabaff!
    • Use httpx.request to allow bodies for all type of requests [#545, #547]. Thanks @MalteBecker!

    Fixes

    • OpenAPI schema validation issues (#426, #568). Thanks @p1-ra!
    • treat period as a delimiter in names (#546). Thanks @alexifm!
    • Non-string header values [#552, #553, #566]. Thanks @John98Zakaria!
    • Generate valid code when a property of a model is named "datetime" [#557 & #558]. Thanks @kmray!
    • Multipart uploads for httpx >= 0.19.0 [#508, #548]. Thanks @skuo1-ilmn & @kairntech!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.8(Dec 19, 2021)

    Features

    • New and improved docstrings in generated functions and classes [#503, #505, #551]. Thanks @rtaycher!
    • Support httpx 0.21.* (#537)

    Fixes

    • Basic types as JSON bodies and responses [#487 & #550]. Thanks @Gelbpunkt!
    • Relative paths to config files [#538 & #544]. Thanks to @motybz, @MalteBecker, & @abhinav-cashify!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.7(Oct 31, 2021)

    Fixes

    • SSL verify argument to async clients [#533 & #510]. Thanks @fsvenson and @mvaught02!
    • Remove unused CHANGELOG from generated setup.py [#529]. Thanks @johnthagen!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.6(Oct 25, 2021)

    Features

    • Improve error messages related to invalid arrays and circular or recursive references [#519].
    • Add httpx 0.20.* support [#514].

    Fixes

    • Use isort "black" profile in generated clients [#523]. Thanks @johnthagen!
    • setup.py should generate importable packages named _client [#492, #520, #521]. Thanks @tedo-benchling & @Leem0sh!
    • Allow None in enum properties [#504, #512, #516]. Thanks @juspence!
    • properly support JSON OpenAPI documents and config files [#488, #509, #515]. Thanks @tardyp and @Gelbpunkt!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.5(Sep 26, 2021)

    Features

    • Add verify_ssl option to generated Client, allowing users to ignore or customize ssl verification (#497). Thanks @rtaycher!

    Fixes

    • Properly label a path template issue as a warning (#494). Thanks @chamini2!
    • Don't allow mixed types in enums.
    • Don't crash when a null is in an enum (#500). Thanks @juspence!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.4(Sep 5, 2021)

    Features

    • Allow customization of post-generation steps with the post_hooks config option.
    • Allow httpx 0.19.* (#481)

    Fixes

    • Don't crash the generator when one of the post-generation hooks is missing [fixes #479]. Thanks @chamini2 and @karolzlot!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.3(Aug 16, 2021)

    Features

    • Expose python_identifier and class_name functions to custom templates to rename with the same behavior as the parser.

    Fixes

    • Treat true and false as reserved words.
    • Prevent generating Python files named the same as reserved / key words.
    • Properly replace reserved words in class and module names [#475, #476]. Thanks @mtovts!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.2(Aug 16, 2021)

    Features

    • Allow path parameters to be positional args [#429 & #464]. Thanks @tsotnikov!
    • Include both UNSET and None static types for nullable or optional query params [#421, #380, #462]. Thanks @forest-benchling!
    • Allow allOf enums to be subsets of one another or their base types [#379, #423, #461]. Thanks @forest-benchling! (#461)

    Fixes

    • Parameters from PathItem can now be overriden in Operation [#458 & #457]. Thanks @mtovts!
    Source code(tar.gz)
    Source code(zip)
  • v.0.10.1(Jul 10, 2021)

  • v.0.10.0(Jul 5, 2021)

    Breaking Changes

    • Normalize generated module names to allow more tags [#428 & #448]. Thanks @iamnoah & @forest-benchling!
    • Improved the consistency of snake_cased identifiers which will cause some to be renamed [#413 & #432]. Thanks @ramnes!
    • Allow more types in multipart payloads by defaulting to JSON for complex types [#372]. Thanks @csymeonides-mf!

    Features

    • Allow custom templates for API and endpoint __init__ files. [#442] Thanks @p1-ra!

    Fixes

    • Treat empty schemas like Any instead of None. Thanks @forest-benchling! [#417 & #445]
    Source code(tar.gz)
    Source code(zip)
  • v.0.9.2(Jun 14, 2021)

    This release is the first release from the new GitHub organization! As such, all the links in the repo have been updated to point at the new URL.

    Features

    • Add option to fail on warning [#427]. Thanks @forest-benchling!

    Fixes

    • Properly strip out UNSET values from form data [#430]. Thanks @p1-ra!
    Source code(tar.gz)
    Source code(zip)
  • v.0.9.1(May 13, 2021)

    Features

    • Allow references to non-object, non-enum types [#371][#418][#425]. Thanks @p1-ra!
    • Allow for attrs 21.x in generated clients [#412]
    • Allow for using any version of Black [#416] [#411]. Thanks @christhekeele!

    Fixes

    • Prevent crash when providing a non-string default to a string attribute. [#414] [#415]
    • Deserialization of optional nullable properties when no value is returned from the API [#420] [#381]. Thanks @forest-benchling!
    Source code(tar.gz)
    Source code(zip)
  • v.0.9.0(May 4, 2021)

    Breaking Changes

    • Some generated names will be different, solving some inconsistencies. (closes #369) (#375) Thanks @ramnes!
    • Change reference resolution to use reference path instead of class name (fixes #342) (#366)
    • If a schema references exactly one other schema in allOf, oneOf, or anyOf that referenced generated model will be used directly instead of generating a copy with another name. (#361)
    • Attributes shadowing any builtin except id and type will now be renamed in generated clients (#360, #378, #407). Thanks @dblanchette and @forest-benchling!

    Features

    • Allow httpx 0.18.x in generated clients (#400)
    • Add summary attribute to Endpoint for use in custom templates (#404)
    • Support common parameters for paths (#376). Thanks @ramnes!
    • Add allOf support for model definitions (#98) (#321)

    Fixes

    • Attempt to deduplicate endpoint parameters based on name and location (fixes #305) (#406)
    • Names of classes without titles will no longer include ref path (fixes #397) (#405). Thanks @ramnes!
    • Problems with enum defaults in allOf (#363). Thanks @csymeonides-mf
    • Prevent duplicate return types in generated api functions (#365)
    • Support empty strings in enums (closes #357) (#358). Thanks @ramnes!
    • Allow passing data with files in multipart. (Fixes #351) (#355)
    • Deserialization of unions (#332). Thanks @forest-benchling!
    Source code(tar.gz)
    Source code(zip)
  • v.0.8.0(Feb 19, 2021)

    Breaking Changes

    • Generated clients will no longer pass through None to query parameters. Previously, any query params set to None would surface as empty strings (per the default behavior of httpx). This is contrary to the defaults indicated by the OpenAPI 3.0.3 spec. Ommitting these parameters makes us more compliant. If you require a style of null to be passed to your query parameters, please request support for the OpenAPI "style" attribute. Thank you to @forest-benchling and @bowenwr for a ton of input on this.

    Additions

    • New --meta command line option for specifying what type of metadata should be generated:
      • poetry is the default value, same behavior you're used to in previous versions
      • setup will generate a pyproject.toml with no Poetry information, and instead create a setup.py with the project info.
      • none will not create a project folder at all, only the inner package folder (which won't be inner anymore)
    • Attempt to detect and alert users if they are using an unsupported version of OpenAPI (#281).
    • The media type application/vnd.api+json will now be handled just like application/json (#307). Thanks @jrversteegh!
    • Support passing models into query parameters (#316). Thanks @forest-benchling!
    • Add support for cookie parameters (#326).
    • New --file-encoding command line option (#330). Sets the encoding used when writing generated files (defaults to utf-8). Thanks @dongfangtianyu!

    Changes

    • Lowered the minimum version of python-dateutil to 2.8.0 for improved compatibility (#298 & #299). Thanks @bowenwr!
    • The from_dict method on generated models is now a @classmethod instead of @staticmethod (#215 & #292). Thanks @forest-benchling!
    • Renamed all templates to end in .jinja, and all python-templates to end in .py.jinja to fix confusion with the latest version of mypy. Note this will break existing custom templates until you update your template file names.

    Fixes

    • Endpoint tags are now sanitized during parsing to fix an issue where My Tag and MyTag are seen as two different tags but are then later unified, causing errors when creating directories. Thanks @p1-ra! (#328)
    • Parser will softly ignore value error during schema responses' status code convertion from string to integer (not a number). Errors will be reported to the end user and parsing will continue to proceed (#327).
    • The generated from_dict and to_dict methods of models will now properly handle nullable and not required properties that are themselves generated models (#315). Thanks @forest-benchling!
    • Fixed a typo in the async example in generated README.md files (#337). Thanks @synchronizing!
    • Fix deserialization of None and Unset properties for all types by unifying the checks (#334). Thanks @forest-benchling!
    • If duplicate model names are detected during generation, you'll now get an error message instead of broken code (#336). Thanks @forest-benchling!
    • Fixes Enum deserialization when the value is UNSET (#306). Thanks @bowenwr!
    Source code(tar.gz)
    Source code(zip)
  • v.0.7.3(Dec 21, 2020)

    Fixes

    • Spacing and extra returns for Union types of additionalProperties (#266 & #268). Thanks @joshzana & @packyg!
    • Title of inline schemas will no longer be missing characters (#271 & #274). Thanks @kalzoo!
    • Handling of nulls (Nones) when parsing or constructing dates (#267). Thanks @fyhertz!
    Source code(tar.gz)
    Source code(zip)
  • v.0.7.2(Dec 9, 2020)

  • v.0.7.1(Dec 8, 2020)

    Additions

    • Support for additionalProperties attribute in OpenAPI schemas and "free-form" objects by adding an additional_properties attribute to generated models. COMPATIBILITY NOTE: this will prevent any model property with a name that would be coerced to "additional_properties" in the generated client from generating properly (#218 & #252). Thanks @packyg!

    Fixes

    • Enums will once again work with query parameters (#259). Thanks @packyg!
    • Generated Poetry metadata in pyproject.toml will properly indicate Python 3.6 compatibility (#258). Thanks @bowenwr!
    Source code(tar.gz)
    Source code(zip)
  • v.0.7.0(Nov 25, 2020)

    Breaking Changes

    • Any request/response field that is not required and wasn't specified is now set to UNSET instead of None.
    • Values that are UNSET will not be sent along in API calls
    • Schemas defined with type=object will now be converted into classes, just like if they were created as ref components. The previous behavior was a combination of skipping and using generic Dicts for these schemas.
    • Response schema handling was unified with input schema handling, meaning that responses will behave differently than before. Specifically, instead of the content-type deciding what the generated Python type is, the schema itself will.
      • As a result of this, endpoints that used to return bytes when content-type was application/octet-stream will now return a File object if the type of the data is "binary", just like if you were submitting that type instead of receiving it.
    • Instead of skipping input properties with no type, enum, anyOf, or oneOf declared, the property will be declared as None.
    • Class (models and Enums) names will now contain the name of their parent element (if any). For example, a property declared in an endpoint will be named like {endpoint_name}_{previous_class_name}. Classes will no longer be deduplicated by appending a number to the end of the generated name, so if two names conflict with this new naming scheme, there will be an error instead.

    Additions

    • Added a --custom-template-path option for providing custom jinja2 templates (#231 - Thanks @erichulburd!).
    • Better compatibility for "required" (whether or not the field must be included) and "nullable" (whether or not the field can be null) (#205 & #208). Thanks @bowenwr & @emannguitar!
    • Support for all the same schemas in responses as are supported in parameters.
    • In template macros: added declare_type param to transform and initial_value param to construct to improve flexibility (#241 - Thanks @packyg!).

    Fixes

    • Fixed spacing and generation of properties of type Union in generated models (#241 - Thanks @packyg!).
    • Fixed usage instructions in generated README.md (#247 - Thanks @theFong!).
    Source code(tar.gz)
    Source code(zip)
  • v.0.7.0-rc.3(Nov 24, 2020)

  • v.0.7.0-rc.2(Nov 18, 2020)

    Additions

    • In template macros: added declare_type param to transform and initial_value param to construct to improve flexibility (#241 - Thanks @packyg!).

    Fixes

    • Fixed spacing and generation of properties of type Union in generated models (#241 - Thanks @packyg!).
    Source code(tar.gz)
    Source code(zip)
Owner
null
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 3k Dec 31, 2022
Sane and flexible OpenAPI 3 schema generation for Django REST framework.

drf-spectacular Sane and flexible OpenAPI 3.0 schema generation for Django REST framework. This project has 3 goals: Extract as much schema informatio

T. Franzel 1.4k Jan 8, 2023
Test utility for validating OpenAPI documentation

DRF OpenAPI Tester This is a test utility to validate DRF Test Responses against OpenAPI 2 and 3 schema. It has built-in support for: OpenAPI 2/3 yaml

snok 106 Jan 5, 2023
Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Matheus Rodrigues 1 Jan 20, 2022
📖 Generate markdown API documentation from Google-style Python docstring. The lazy alternative to Sphinx.

lazydocs Generate markdown API documentation for Google-style Python docstring. Getting Started • Features • Documentation • Support • Contribution •

Machine Learning Tooling 118 Dec 31, 2022
Python script to generate Vale linting rules from word usage guidance in the Red Hat Supplementary Style Guide

ssg-vale-rules-gen Python script to generate Vale linting rules from word usage guidance in the Red Hat Supplementary Style Guide. These rules are use

Vale at Red Hat 1 Jan 13, 2022
Python Tool to Easily Generate Multiple Documents

Python Tool to Easily Generate Multiple Documents Running the script doesn't require internet Max Generation is set to 10k to avoid lagging/crashing R

null 2 Apr 27, 2022
A Python Package To Generate Strong Passwords For You in Your Projects.

shPassGenerator Version 1.0.6 Ready To Use Developed by Shervin Badanara (shervinbdndev) on Github Language and technologies used in This Project Work

Shervin 11 Dec 19, 2022
Generate a single PDF file from MkDocs repository.

PDF Generate Plugin for MkDocs This plugin will generate a single PDF file from your MkDocs repository. This plugin is inspired by MkDocs PDF Export P

null 198 Jan 3, 2023
Generate YARA rules for OOXML documents using ZIP local header metadata.

apooxml Generate YARA rules for OOXML documents using ZIP local header metadata. To learn more about this tool and the methodology behind it, check ou

MANDIANT 34 Jan 26, 2022
Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

Introduction Swagger UI allows anyone — be it your development team or your end consumers — to visualize and interact with the API’s resources without

Swagger 23.2k Dec 29, 2022
A collection of simple python mini projects to enhance your python skills

A collection of simple python mini projects to enhance your python skills

PYTHON WORLD 12.1k Jan 5, 2023
Python Eacc is a minimalist but flexible Lexer/Parser tool in Python.

Python Eacc is a parsing tool it implements a flexible lexer and a straightforward approach to analyze documents.

Iury de oliveira gomes figueiredo 60 Nov 16, 2022
Repository for learning Python (Python Tutorial)

Repository for learning Python (Python Tutorial) Languages and Tools ?? Overview ?? Repository for learning Python (Python Tutorial) Languages and Too

Swiftman 2 Aug 22, 2022
A python package to avoid writing and maintaining duplicated python docstrings.

docstring-inheritance is a python package to avoid writing and maintaining duplicated python docstrings.

Antoine Dechaume 15 Dec 7, 2022
advance python series: Data Classes, OOPs, python

Working With Pydantic - Built-in Data Process ========================== Normal way to process data (reading json file): the normal princiople, it's f

Phung Hưng Binh 1 Nov 8, 2021
A comprehensive and FREE Online Python Development tutorial going step-by-step into the world of Python.

FREE Reverse Engineering Self-Study Course HERE Fundamental Python The book and code repo for the FREE Fundamental Python book by Kevin Thomas. FREE B

Kevin Thomas 7 Mar 19, 2022
A simple USI Shogi Engine written in python using python-shogi.

Revengeshogi My attempt at creating a USI Shogi Engine in python using python-shogi. Current State of Engine Currently only generating random moves us

null 1 Jan 6, 2022
Python-slp - Side Ledger Protocol With Python

Side Ledger Protocol Run python-slp node First install Mongo DB and run the mong

Solar 3 Mar 2, 2022