Reorder logic in api.py