Service management is an essential component of a stable API Ecosystem.
Basic compontents for service management are communicating:
when you are not operational, and explicit how long it will take to be up and running again;
if they are over quota and prevent overquota via throttling headers.
While it could be annoying to explicitly state that every response should contain throttling headers, you can use yaml anchors for that!
x-commons:
throttling-headers: &throttling-headers
X-RateLimit-Limit:
$ref: ..
X-RateLimit-Remaining:
$ref: ..
X-RateLimit-Reset:
$ref: ..
Now we can use the anchor in our get /echo responses
paths:
/echo
get:
...
operationId: api.get_echo
responses:
'200':
headers:
<<: *throttling_headers
...
Modify the ex-07-01-throttling.yaml spec so that:
get /echo responses returns the throtting headers in case of 200;429 response is returned
In [4]:
# Decorate with `throttle`
from oas3.throttling_quota import throttle
@throttle
def f(user='foo'):
return {}, 200, {}
In [5]:
# Or write your own using
from oas3.throttling_quota import ThrottlingQuota
quotas = ThrottlingQuota(ttl=30, limit=3)
for i in range(4):
ret = quotas.consume(user=f'user1')
print(ret)
Modify api.py:get_echo such that:
429 is returned;the throttling infos are returned as integers in every response:
Now run the spec in a terminal using
cd /code/notebooks/oas3/
connexion run /code/notebooks/oas3/ex-07-01-throttling-ok.yaml
play a bit with the Swagger UI
and try making a request!
In [ ]:
!curl http://localhost:5000/datetime/v1/echo -kv -ufoo:foo
In [ ]: