11import requests
22
33from gophish .models import Error
4-
54'''
65api.py
76
87Base API endpoint class that abstracts basic CRUD operations.
98'''
109
10+
1111class APIEndpoint (object ):
1212 """
1313 Represents an API endpoint for Gophish, containing common patterns
1414 for CRUD operations.
1515 """
16+
1617 def __init__ (self , api , endpoint = None , cls = None ):
1718 """ Creates an instance of the APIEndpoint class.
1819
@@ -25,20 +26,30 @@ def __init__(self, api, endpoint=None, cls=None):
2526 self .endpoint = endpoint
2627 self ._cls = cls
2728
28- def get (self , resource_id = None , resource_action = None ):
29+ def get (self ,
30+ resource_id = None ,
31+ resource_action = None ,
32+ resource_cls = None ,
33+ single_resource = False ):
2934 """ Gets the details for one or more resources by ID
3035
3136 Args:
3237 cls - gophish.models.Model - The resource class
3338 resource_id - str - The endpoint (URL path) for the resource
3439 resource_action - str - An action to perform on the resource
40+ resource_cls - cls - A class to use for parsing, if different than the base resource
41+ single_resource - bool - An override to tell Gophish that even
42+ though we aren't requesting a single resource, we expect a single response object
3543
3644 Returns:
3745 One or more instances of cls parsed from the returned JSON
3846 """
3947
4048 endpoint = self .endpoint
4149
50+ if not resource_cls :
51+ resource_cls = self ._cls
52+
4253 if resource_id :
4354 endpoint = '{}/{}' .format (endpoint , resource_id )
4455
@@ -49,10 +60,10 @@ def get(self, resource_id=None, resource_action=None):
4960 if not response .ok :
5061 return Error .parse (response .json ())
5162
52- if resource_id :
53- return self . _cls .parse (response .json ())
63+ if resource_id or single_resource :
64+ return resource_cls .parse (response .json ())
5465
55- return [self . _cls .parse (resource ) for resource in response .json ()]
66+ return [resource_cls .parse (resource ) for resource in response .json ()]
5667
5768 def post (self , resource ):
5869 """ Creates a new instance of the resource.
@@ -61,8 +72,9 @@ def post(self, resource):
6172 resource - gophish.models.Model - The resource instance
6273
6374 """
64- response = self .api .execute ("POST" , self .endpoint , json = (resource .as_dict ()))
65-
75+ response = self .api .execute (
76+ "POST" , self .endpoint , json = (resource .as_dict ()))
77+
6678 if not response .ok :
6779 return Error .parse (response .json ())
6880
@@ -74,7 +86,7 @@ def put(self, resource):
7486 Args:
7587 resource - gophish.models.Model - The resource instance
7688 """
77-
89+
7890 endpoint = self .endpoint
7991
8092 if resource .id :
0 commit comments