Skip to main content
BasicReturns fits naturally in any application layer that calls external APIs or needs to return structured responses. The to_dict() method produces a plain dictionary with a consistent shape — ok, error, msg, data — that can be handed directly to a JSON serializer, a framework response object, or a message queue. There is no translation layer to write, and callers always know what to expect.

Wrapping an HTTP Client

The fetch_api_data pattern from the BasicReturns README shows how to wrap a requests call. Initialize the response, attempt the request inside try, and catch requests.exceptions.RequestException on failure:
raise_for_status() converts HTTP error codes into exceptions, which are then caught and stored in response.error. The caller never needs to inspect status codes — result.ok is the single signal.

Serializing for API Responses

Call result.to_dict() to get a plain dictionary ready for serialization. The structure is always the same regardless of success or failure:
The consistent shape means your frontend or downstream consumers can always read ok first and branch from there — no need to special-case error response formats.
The data field in to_dict() returns {} (an empty dictionary) when data is None. This keeps API responses well-formed even on partial success or failure — JSON clients receive a valid object for data rather than null, which avoids null-check errors in many frontend frameworks.

Flask Example

In a Flask route, call the service function, then pass result.to_dict() directly to jsonify. The HTTP status code can be derived from result.ok:
The route handler stays thin: it delegates to the service layer, converts the result to a dictionary, and maps ok to an HTTP status code. No try/except blocks appear in the handler at all.

FastAPI Example

FastAPI works the same way. Because DataAndMsgReturn is a Pydantic BaseModel, you can return the model instance directly from an endpoint and FastAPI will serialize it automatically — or call to_dict() if you prefer an explicit dictionary response:
Because DataAndMsgReturn extends Pydantic’s BaseModel, FastAPI can generate accurate OpenAPI schema from it automatically when you use Option 1, giving you free documentation for the response shape.
Set response.msg to a user-facing message and store the raw exception in response.error. Log response.error server-side for debugging, but return only response.msg to the client in your response body. This keeps sensitive implementation details — file paths, stack frames, internal service names — out of public API responses while preserving them where they are actually useful.