openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

Generating python client using asyncio library does not generate examples showcasing the usage of asyncio

Open prathik457 opened this issue 8 years ago • 10 comments

Description

I am planning to use asyncio in a python client and I see that documentation is not provided for the usage of asyncio

openapi-generator version

3.2.0

OpenAPI declaration file content or url
Command line used for generation
java -jar openapi-generator-cli-3.2.0.jar generate 
                              -i api.yml 
                              -g python 
                              -o some-client 
                              --library asyncio
Steps to reproduce

I checked the main readme.md and also the docs to check for the documentation of asyncio

Related issues/PRs
Suggest a fix/enhancement

I suggest we should give asyncio usage in the documentation. There will be clarity implementation wise.

prathik457 avatar Aug 07 '18 15:08 prathik457

@prathik457 thanks for reporting the issue. We can update the code sample according for other libraries "asyncio", "tornado".

Let's start with one method: https://github.com/OpenAPITools/openapi-generator/blob/master/samples/client/petstore/python-asyncio/docs/PetApi.md#get_pet_by_id

from __future__ import print_function
import time
import petstore_api
from petstore_api.rest import ApiException
from pprint import pprint

# Configure API key authorization: api_key
configuration = petstore_api.Configuration()
configuration.api_key['api_key'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['api_key'] = 'Bearer'

# create an instance of the API class
api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration))
pet_id = 56 # int | ID of pet to return

try:
    # Find pet by ID
    api_response = api_instance.get_pet_by_id(pet_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling PetApi->get_pet_by_id: %s\n" % e)

What should be the correct looks like so that we can fix the mustache template accordingly?

cc @taxpon (2017/07) @frol (2017/07) @mbohlool (2017/07) @cbornet (2017/09) @kenjones-cisco (2017/11)

wing328 avatar Aug 07 '18 17:08 wing328

Can anyone post an example usage? This would be helpful.

lk-jeffpeck avatar Dec 10 '19 21:12 lk-jeffpeck

@Jyhess any help here? :)

rafalkrupinski avatar Dec 22 '19 18:12 rafalkrupinski

The main difference for usage is that it should be

api_response = await api_instance.get_pet_by_id(pet_id)

but that also requires you to be in a coroutine, i.e. async def, so you can't really just do it as a module-level block of code like that, except possibly in Python 3.8 with the new -m asyncio support.

TBBle avatar Mar 06 '20 06:03 TBBle

Also worth noting that asyncio is Python 3 only, so we can drop

from __future__ import print_function

in this case.

TBBle avatar Mar 06 '20 09:03 TBBle

To answer the question:

  • methods in the api are async, even though are not declared as such, so you must use asyncio event loop
  • when using "synchronous" (async_req=False) version:
    • must call API from within an asyncio.Task (otherwise you get an error from aiohttp)
    • you get the result either within that task with await, or from the task object t.result()
  • in case of "asynchronous" (async_req=True)
    • no need to run in Task
    • api calls return a mp.pool.ApplyResult, get the result with await obj.get()
    • the ApiClient is an async context manager, so you can use it to close the pool

rafalkrupinski avatar Apr 04 '20 16:04 rafalkrupinski

@rafalkrupinski:

async_req=True doesn't currently work with asyncio, see #5539. It never awaits the request, so will never receive a response, and will raise a RuntimeWarning on event loop termination.

~~Pool closure is not currently correct, see #5538. It's not actually done with the AsyncContextManager, it defers the closure until "later", and that can easily be after the event loop has been closed.~~ Fixed in 4.3.0 release.

Edit: I reread your comment, and realised you're working around that bug by manually awaiting the object returned. In this case, only coroutine creation was done in the thread, and then the thread was immediately joined. You've actually done the work of the request back in the same thread, so there's no difference in using async_req=True than async_req=False except you have to write less-natural await in the former, and you've spent resources on a threaded action for no good reason.

I'm also not sure why you needed to put your use-cases in an asyncio.Task, I didn't see that need here. I'm not sure which t you're talking about in t.result(), unless you've also got code hooked up to call set_result on some task when your awaited request completes? That's certainly possible, but should in no way be mandatory.


In summary, for this issue, the actual usage changes needed are minimal (as I gave above) but there are some bugs to fix as well.

TBBle avatar Apr 06 '20 03:04 TBBle

@TBBle I think you're right about calling with async_req=True

Calling with async_req=True outside of a task got me this exception coming from aiohttp: RuntimeError: Timeout context manager should be used inside a task

rafalkrupinski avatar Apr 06 '20 10:04 rafalkrupinski

The issue is active since 2018 :( Any news?

Olegt0rr avatar Jul 15 '21 07:07 Olegt0rr

A few years later... This is how I consume the generated APIs in the async way. First of all a function that wraps an API call:

import asyncio
...
async def async_api_call(api_call: Callable, *args, **kwargs):
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(
        None, lambda: api_call(*args, async_req=True, **kwargs).get()
    )
    return result

Now, this is how to call the API either in sync or async way:

from my_py_sdk import (
    ApiClient,
    Configuration,
)
from my_py_sdk.apis import SomeApi
...
config = Configuration()
config.host = "http://localhost:5000"
some_api = SomeApi(ApiClient(config))

# sync way
item = some_api.get_item_by_id(5)

# async way
async def get_item_from_api(id: int):
    return await async_api_call(some_api.get_item_by_id, id)

quantotto avatar Apr 15 '25 09:04 quantotto