Designing APIs with Flask: the Ez Way
Sup people, I was designing an API yesterday, and I was like this takes too long. Coding should be fun, so here’s what I’ve done to make it ez and fun again.
U gotta know some python3 (functions, decorators & asterisk magic) to understand the following.
So the basic idea is that I’ll write an api
decorator rather than using app.route
every time.
Ez flask is the way to go
So let’s talk about the mess above. First, I create a restricted
decorator so that all calls to my api will need a username and a password. *args
and **kwargs
allow me to pass all the extra parameters to the decorated function.
The api
decorator handles the app.route
for me. That function.__name__
is the name of the function that is being decorated (i.e. update).
Another interesting method is that I’ve taken the extra arguments in path format ( <path:otherArgs>
) and parsed it.
Another trick
If you’re tired of writing prints all over your code, then I got another treat for you.
DEBUG = True
def dbg_print(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
Voila! Now you can turn ’em off. (Wanna learn more about starry stuff.)
If you learned something new, consider 👏. Please comment your improvements and modifications.