openapi-generators / openapi-generators/openapi-python-client

Generates invalid python code for seemingly correct json

Aperta
#1,425 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
Python
Stelle
2k
Fork
293
Merge medio
34m
PR unite (30g)
1

Descrizione

Describe the bug
generator around primitives in request body fails
OpenAPI Spec File
I cannot share the full spec but this is an excempt:

    "/api/helloworlduser/{externalId}/something": {
      "patch": {
        "tags": [
          "UpdateHelloWorldUser"
        ],
        "description": "Update user",
        "operationId": "HelloWorldUserUpdate",
        "parameters": [
          {
            "name": "externalId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "number",
                "format": "double",
                "nullable": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserReadDTO"
                }
              }
            }
          }
        }
      }
    },

this generates the file:

from http import HTTPStatus
from typing import Any, cast
from urllib.parse import quote

import httpx

from ...client import AuthenticatedClient, Client
from ...types import Response, UNSET
from ... import errors

from ...models.user_read_dto import UserReadDTO
from ...types import UNSET, Unset
from typing import cast



def _get_kwargs(
    external_id: str,
    *,
    body: float | None | Unset = UNSET,

) -> dict[str, Any]:
    headers: dict[str, Any] = {}


    

    

    _kwargs: dict[str, Any] = {
        "method": "patch",
        "url": "/api/helloworlduser/{external_id}/something".format(external_id=quote(str(external_id), safe=""),),
    }

    
    else:
        _kwargs["json"] = body


    headers["Content-Type"] = "application/json"

    _kwargs["headers"] = headers
    return _kwargs



def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> UserReadDTO | None:
    if response.status_code == 200:
        response_200 = UserReadDTO.from_dict(response.json())



        return response_200

    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None


def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[UserReadDTO]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )


def sync_detailed(
    external_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: float | None | Unset = UNSET,

) -> Response[UserReadDTO]:
    """  Update user

    Args:
        external_id (str):
        body (float | None | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[UserReadDTO]
     """


    kwargs = _get_kwargs(
        external_id=external_id,
body=body,

    )

    response = client.get_httpx_client().request(
        **kwargs,
    )

    return _build_response(client=client, response=response)

def sync(
    external_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: float | None | Unset = UNSET,

) -> UserReadDTO | None:
    """  Update user

    Args:
        external_id (str):
        body (float | None | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        UserReadDTO
     """


    return sync_detailed(
        external_id=external_id,
client=client,
body=body,

    ).parsed

async def asyncio_detailed(
    external_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: float | None | Unset = UNSET,

) -> Response[UserReadDTO]:
    """  Update user

    Args:
        external_id (str):
        body (float | None | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[UserReadDTO]
     """


    kwargs = _get_kwargs(
        external_id=external_id,
body=body,

    )

    response = await client.get_async_httpx_client().request(
        **kwargs
    )

    return _build_response(client=client, response=response)

async def asyncio(
    external_id: str,
    *,
    client: AuthenticatedClient | Client,
    body: float | None | Unset = UNSET,

) -> UserReadDTO | None:
    """  Update user

    Args:
        external_id (str):
        body (float | None | Unset):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        UserReadDTO
     """


    return (await asyncio_detailed(
        external_id=external_id,
client=client,
body=body,

    )).parsed

which is a complete broken file (see the else in get_kwargs).

Desktop (please complete the following information):

  • OS: mac os
  • Python Version: 3.14
  • openapi-python-client version: 0.28.3

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproducete il problema con l’estratto OpenAPI fornito usando openapi-python-client 0.28.3, quindi tracciate la generazione del corpo della richiesta per gli schemi primitivi nullable. Il payload non indica alcun file del repository né alcun test; il lavoro è completato quando il modulo dell’endpoint generato è sintatticamente valido e gestisce il corpo della richiesta primitivo senza l’else orfano mostrato nel report.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
openapi, python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
55/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.