Sobes.tech
Junior — Middle

What methods are used to implement API projection for various purposes?

sobes.tech AI

Answer from AI

API projection is the creation of different representations or interfaces of the same functionality for various purposes or clients. In Python, this is implemented in several ways:

  • Wrappers: functions or classes that hide complexity and provide a simplified interface.
  • Decorators: allow modifying the behavior of functions or methods, creating different API variants.
  • API versioning: supporting multiple API versions with different sets of methods or parameters.
  • Using serialization and schemas (e.g., with Pydantic, Marshmallow) to form different data representations.
  • Filtering and adapting data: returning different fields or data structures depending on the client.

An example of a simple wrapper:

class FullAPI:
    def get_data(self):
        return {'id': 1, 'name': 'Item', 'secret': 'hidden'}

class PublicAPI:
    def __init__(self, full_api):
        self.full_api = full_api

    def get_data(self):
        data = self.full_api.get_data()
        # Projection: remove the 'secret' field
        data.pop('secret', None)
        return data

full_api = FullAPI()
public_api = PublicAPI(full_api)
print(public_api.get_data())  # {'id': 1, 'name': 'Item'}

Thus, API projection allows adapting the interface for different needs while maintaining the overall logic.