Fix file io exceptions and race conditions in api.py