Clean up api.py, various fixes