Skip to content

Instantly share code, notes, and snippets.

@Ishtiaq11
Created February 14, 2023 06:41
Show Gist options
  • Save Ishtiaq11/e3dafe5f1b804ebece187ee2ff3adb05 to your computer and use it in GitHub Desktop.
Save Ishtiaq11/e3dafe5f1b804ebece187ee2ff3adb05 to your computer and use it in GitHub Desktop.
class MicroserviceClient:
def __init__(self, base_url):
self.base_url = base_url
def make_request(self, endpoint, method, **kwargs):
"""
Make a request to the microservice.
"""
try:
url = f"{self.base_url}/{self.endpoint}"
response = requests.request(method, url, **kwargs)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as err:
raise MicroserviceError(err)
except json.JSONDecodeError as e:
raise ValueError("Invalid JSON: " + e.msg)
class ExampleService(MicroserviceClient):
def __init__(self):
super().__init__(settings.EXAMPLE_SERVICE_BASE_URL)
def get_example(self, example_id):
"""
Get an example from the microservice.
"""
endpoint = f"{self.endpoint}/{example_id}"
return self.make_request("GET", endpoint=endpoint)
def create_example(self, data):
"""
Create a new example in the microservice.
"""
return self.make_request("POST", json=data)
class UserServiceClient(MicroserviceClient):
def create_user(self, data):
endpoint = "users"
return self.make_request(endpoint, method="POST", data=data)
def update_user(self, data):
endpoint = "users"
return self.make_request(endpoint, method="PUT", data=data)
def get_user(self, user_id):
endpoint = f"users/{user_id}"
return self.make_request(endpoint)
def delete_user(self, user_id):
endpoint = f"users/{user_id}"
return self.make_request(endpoint, method="DELETE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment