1

I have simple function that takes an arbitrary number of arguments like so:

def greet(*args):
    a=list(args)
    return {"greetings to  users:": a}

greet('Aron','Claus')
>>>{'greetings to  users:': ['Aron', 'Claus']}

The function works as expected. But when i put a router decorator on the function like so:

@router.get("/greet")
def greet(*args):
    a=list(args)
    return {"greetings to  users:": a}

I get an internal server error on swagger side and my commandline gives me the following error:

TypeError: greet() got an unexpected keyword argument 'args'

Why is this happening how can I avoid this error. Thanks in advance

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
ttuff
  • 45
  • 5
  • What are you expecting `args` to represented in a web context? How are you expecting to pass this value through web? – MatsLindh Oct 28 '22 at 19:47
  • I am new to web development. I want to pass a list of arbitrary length to the greet function and thought it would be most concise to use `args` – ttuff Oct 29 '22 at 02:57
  • 1
    Yes, but _where are these arguments coming from_. Since you want to expose this through FastAPI, these arguments are apparently coming from a web context. So how do you want to invoke `greet` from the web, and how are you planning on providing those arguments through a web service? This is important since you have to define _how the arguments should be provided_ when you expose a function as route function; are these provided as GET parameters in the URL (`/path?foo=bar&baz=bar`), as POST parameters or submitted as JSON? You can't define a "catch all" argument in this way then, since FastAPI – MatsLindh Oct 29 '22 at 10:41
  • .. needs you to give it some information about _where_ the parameters should come from and what their expected type is - so that it can validate the request for you and convert the values into the expected format for your function. – MatsLindh Oct 29 '22 at 10:42
  • Does this answer your question? [How to allow any arbitrary query parameters using FastAPI and Swagger?](https://stackoverflow.com/questions/68821077/how-to-allow-any-arbitrary-query-parameters-using-fastapi-and-swagger) – Chris Oct 29 '22 at 12:34
  • Additionally, please have a look [here](https://stackoverflow.com/a/70636163/17865804), as well as [here](https://stackoverflow.com/a/73761724/17865804) and [here](https://stackoverflow.com/a/71741617/17865804) on how to submit JSON data to a FastAPI backend. – Chris Oct 29 '22 at 12:40

1 Answers1

0

So what i found is the following from the Fastapi documentation

from typing import List, Union

from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: Union[List[str], None] = Query(default=None)):
    query_items = {"q": q}
    return query_items

The URL would be like: http://localhost:8000/items/?q=foo&q=bar

It works fine.

ttuff
  • 45
  • 5