6.6. FastAPI GET

  • Resources

  • Query Parameters

6.6.1. SetUp

>>> from fastapi import FastAPI
>>> app = FastAPI()

6.6.2. No Parameters

  • Does define resource (required)

  • /hello

>>> @app.get('/hello')
... def hello():
...     return {'data': 'hello'}
$ curl http://127.0.0.1:8000/hello
{"data":"hello"}

6.6.3. Single Path - One

  • Does define resource (required)

  • /hello/{firstname}

>>> @app.get('/hello/{firstname}')
... def hello(firstname: str):
...     return {'data': firstname}
$ curl http://127.0.0.1:8000/hello/Mark
{"data":"Mark"}

6.6.4. Path Parameter - Many

  • Does define resource (required)

  • /hello/{firstname}-{lastname}

>>> @app.get('/hello/{firstname}-{lastname}')
... def hello(firstname: str, lastname: str):
...     return {'data': f'{firstname} {lastname}'}
$ curl http://127.0.0.1:8000/hello/Mark-Watney
{"data":"Mark Watney"}

6.6.5. Query Parameter

  • Does not require a name in URL resource, but requires a parameter

  • /hello

>>> @app.get('/hello')
... def hello(firstname: str):
...     return {'data': firstname}
$ curl http://127.0.0.1:8000/hello?firstname=Mark
{"data":"Mark"}

6.6.6. Multiple Parameters

  • Does not require a name in URL resource, but requires a parameter

  • /hello

>>> @app.get('/hello')
... def hello(firstname: str, lastname: str):
...     return {'data': f'{firstname} {lastname}'}
$ curl http://127.0.0.1:8000/hello?firstname=Mark&lastname=Watney
{"data":"Mark Watney"}

6.6.7. Default Values

>>> @app.get('/hello')
... def hello(firstname: str, lastname: str, age: int = 40):
...     return {'data': f'{firstname} {lastname} is {age} years old'}
$ curl http://127.0.0.1:8000/hello/?firstname=Mark&lastname=Watney
{"data":"Mark Watney is 40 years old"}
$ curl http://127.0.0.1:8000/hello/?firstname=Mark&lastname=Watney&age=69
{"data":"Mark Watney is 69 years old"}

6.6.8. Optional

>>> @app.get('/hello/')
... def hello(firstname: str, lastname: str, age: int | None = None):
...     return {'data': f'{firstname} {lastname} is {age} years old'}
$ curl http://127.0.0.1:8000/hello/?firstname=Mark&lastname=Watney
{"data":"Mark Watney is None years old"}
$ curl http://127.0.0.1:8000/hello/?firstname=Mark&lastname=Watney&age=69
{"data":"Mark Watney is 69 years old"}