How to describe parameter in API call


#1

Hey there,

I am very excited to see that the automatic API documentation was reimplemented. Unfortunately I do struggle a bit when it comes to filling out the parameter description field. I figured out that the docstring will be automatically extracted but did not find any overview the documentation of the query parameter (see attached screenshot).

Best
Josh


#2

Also it would be nice if the doc-string of a component could be added to the endpoint’s description e.g.:

class Admin:
    """requires administrator privileges"""
    # ...

class AdminComponent(Component):
    def reslove(self, authorization: http.Header) -> Admin:
        # ...
        return Admin(...)

def my_end_point(admin: Admin):
     # ...

routes = [Route('/my/end/point', 'GET', my_end_point)]

Than /my/end/point/ should have the requires administrator privileges somewhere in its description


#3

@jgoerner Those descriptions showed up for me once I wrote a types.Type-derived class, and provided the description params to validators instantiated for its attributes. The class is then used as type hint for the view handler parameter representing the query params:

class MyRequestParams(types.Type):
    content = validators.String(max_length=1024 * 1024 * 10, description='Text content to tag')
    offset = validators.Integer(minimum=0, allow_null=True, description='Paging offset')
    limit = validators.Integer(minimum=1, allow_null=True, description='Paging limit')

def my_handler(params: MyRequestParams) -> dict:
    pass

This works for request body validation, I haven’t found a way to do the same for URL query parameters / parameters dict you would annotate as http.QueryParam/http.QueryParams.


#4

I’m having the same issue.

So there is no way to validate http.QueryParams in the framework? I just get a 400 with a message of “Must be an object.” when trying to validate query params. The api doc even says they should be passed in as part of the query string, but it doesn’t work:

“Query Parameters
The following parameters should be included as part of a URL query string.”


#5

Outstanding!

This was exactly what I was looking for. Unfortunately I run into the same issue as @silver8ack.

Best
Joshua


#6

@silver8ack

It’s a hack as simple as:

from apistar import validators, http, Route, App, TestClient
from apistar.exceptions import ValidationError
from apistar.types import Type


class TestType(Type):
    a = validators.String(allow_null=False, min_length=1, max_length=5)
    b = validators.String(
        allow_null=True, min_length=1, max_length=5, default="__default__"
    )


def handler(qs: http.QueryParams) -> dict:
    print(f"QS: {dict(qs)}")
    return dict(TestType(**dict(qs)))


routes = [Route("/", method="GET", handler=handler)]
app = App(routes=routes)

client = TestClient(app=app)

# good
response = client.get("/?a=a&b=b")
print(f"{response.status_code}: {response.content}")

# good
response = client.get("/?a=a")
print(f"{response.status_code}: {response.content}")

# Bad
try:
    bad_response = client.get("/?b=a")
except ValidationError as exc:
    print(f"Error: {exc}")

# Bad
try:
    bad_response = client.get("/?a=123456&b=")
except ValidationError as exc:
    print(f"Error: {exc}")

# Bad
try:
    bad_response = client.get("/?a=123456&b=123456")
except ValidationError as exc:
    print(f"Error: {exc}")

if you run with python this code this is the output:

QS: {'a': 'a', 'b': 'b'}
200: b'{"a":"a","b":"b"}'
QS: {'a': 'a'}
200: b'{"a":"a","b":"__default__"}'
QS: {'b': 'a'}
Error: {'a': 'The "a" field is required.'}
QS: {'a': '123456'}
Error: {'a': 'Must have no more than 5 characters.'}
QS: {'a': '123456', 'b': '123456'}
Error: {'a': 'Must have no more than 5 characters.', 'b': 'Must have no more than 5 characters.'}

And no, it’s not yet included as neat feature, there is another post with direct Validator annotations (which honestly is almost identical to check on Types in QueryParams, in fact uses the query_params, but needed more deeper changes at Injector level):

There is no plan to PR all of this unless the authors are eager to tough.