Skip to content

MAPIService base class

Base class of every MAPI services that manages REST request commands

Source code in restmapi\restmapi\services.py
class MAPIService:
	""" Base class of every MAPI services that manages REST request commands
	"""
	def __init__(self, url = None):
		"""Construct a MAPIService from its base url.

		Parameters
		----------
		url : string, optional
			Base url from the service, by default the url is construct using environment variable MAPI_DEFAULT_URL or MAPI registry parameters else "http://localhost:80". 

		Raises
		------
		Exception
			If MAPI REST API is not activvated and url is not specified.
		"""
		if url == None:
			url = os.getenv('MAPI_DEFAULT_URL', None)					
		self._mapi_base_url = url
		if url == None:        			
			protocol = "http"
			hostname = "localhost"
			port = 80
			try:
				import winreg				
				key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\D2T\MORPHEE")
				protocol = winreg.QueryValueEx(key, "RESTProtocol")[0]
				hostname = winreg.QueryValueEx(key, "RESTServerName")[0]
				port = winreg.QueryValueEx(key, "RestPort")[0]
			except:
				pass
			if port == 0:
				raise Exception("REST MAPI is not activated. Go to UEditor MAPI configuration and set a REST port different from 0!")
			if protocol == "":
				protocol = "http"
			if hostname == "":
				hostname = "localhost"	
			self._mapi_base_url = f"{protocol}://{hostname}:{port}"

	@property
	def mapi_base_url(self) -> str:
		""" Base url of the MAPI object
		"""				
		return self._mapi_base_url			

	def invoke_web_request(self, sub_url, method="Get", body=None, raw=False):
		"""Invoke a REST request to the mapi service.

		Parameters
		----------
		sub_url : string
			Sub url to be added to mapi_base_url (including the query parameters if needed)
		method : string, optional
			Common REST verb (Get, Post, Delete, ...), by default "Get"
		body : object, optional
			Object to be added the body, by default None
		raw : bool, optional
			Define the format content, by default False. If true, the web request result is returned. Else, the body and the result are in json format and automatically parsed.

		Returns
		-------
		object
			The result of the REST request converted from json if raw is False

		Raises
		------
		Exception
			Sent by the server (in case of status code 500). The exception contains a json object with the server description
		Exception
			Sent when the status code is different from 200.
		Exception
			Sent when format is wrong (only if raw is False)
		"""
		url = f"{self._mapi_base_url}/{sub_url}".rstrip("/")

		if body is not None:
			if raw:
				res = requests.request(method, url, data=body)
			else:
				res = requests.request(method, url, json=body, headers={"Content-Type": "application/json"})
		else:
			res = requests.request(method, url)
		if  not raw and res.status_code == 500 and res.headers.get("Content-Type") and "json" in res.headers.get("Content-Type"):
			raise Exception(res.json())
		if res.status_code != 200:
			raise Exception(f"invoke_web_request on {url} error:status = {res.status_code}") 
		if not raw and res.headers.get("Content-Type") and "json" not in res.headers.get("Content-Type"):
			raise Exception(f"invoke_web_request on {url} error: bad content type = {res.headers.get('Content-Type')}")		
		if raw:
			return res
		else:
			if res.text == None or res.text == "":
				return None				
			return res.json()

	def invoke_web_get_request(self, sub_url):
		"""Invoke REST request with verb GET to the mapi service.

		Parameters
		----------
		sub_url : string
			Sub url to be added to mapi_base_url (including the query parameters if needed)

		Returns
		-------
		object
			The result of the REST request converted from json

		Raises
		------
		Exception
			Sent by the server (in case of status code 500). The exception contains a json object with the server description
		Exception
			Sent when the status code is different from 200.
		Exception
			Sent when format is wrong
		"""
		return self.invoke_web_request(sub_url)

	def invoke_web_post_request(self, sub_url):
		"""Invoke REST request with verb POST to the mapi service.

		Parameters
		----------
		sub_url : string
			Sub url to be added to mapi_base_url (including the query parameters if needed)

		Returns
		-------
		object
			The result of the REST request converted from json

		Raises
		------
		Exception
			Sent by the server (in case of status code 500). The exception contains a json object with the server description
		Exception
			Sent when the status code is different from 200.
		Exception
			Sent when format is wrong
		"""
		return self.invoke_web_request(sub_url, "POST")

mapi_base_url property

Base url of the MAPI object

__init__(url=None)

Construct a MAPIService from its base url.

Parameters:

  • url (string, default: None ) –
    Base url from the service, by default the url is construct using environment variable MAPI_DEFAULT_URL or MAPI registry parameters else "http://localhost:80".
    

Raises:

  • Exception

    If MAPI REST API is not activvated and url is not specified.

Source code in restmapi\restmapi\services.py
def __init__(self, url = None):
	"""Construct a MAPIService from its base url.

	Parameters
	----------
	url : string, optional
		Base url from the service, by default the url is construct using environment variable MAPI_DEFAULT_URL or MAPI registry parameters else "http://localhost:80". 

	Raises
	------
	Exception
		If MAPI REST API is not activvated and url is not specified.
	"""
	if url == None:
		url = os.getenv('MAPI_DEFAULT_URL', None)					
	self._mapi_base_url = url
	if url == None:        			
		protocol = "http"
		hostname = "localhost"
		port = 80
		try:
			import winreg				
			key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"Software\D2T\MORPHEE")
			protocol = winreg.QueryValueEx(key, "RESTProtocol")[0]
			hostname = winreg.QueryValueEx(key, "RESTServerName")[0]
			port = winreg.QueryValueEx(key, "RestPort")[0]
		except:
			pass
		if port == 0:
			raise Exception("REST MAPI is not activated. Go to UEditor MAPI configuration and set a REST port different from 0!")
		if protocol == "":
			protocol = "http"
		if hostname == "":
			hostname = "localhost"	
		self._mapi_base_url = f"{protocol}://{hostname}:{port}"

invoke_web_get_request(sub_url)

Invoke REST request with verb GET to the mapi service.

Parameters:

  • sub_url (string) –
    Sub url to be added to mapi_base_url (including the query parameters if needed)
    

Returns:

  • object

    The result of the REST request converted from json

Raises:

  • Exception

    Sent by the server (in case of status code 500). The exception contains a json object with the server description

  • Exception

    Sent when the status code is different from 200.

  • Exception

    Sent when format is wrong

Source code in restmapi\restmapi\services.py
def invoke_web_get_request(self, sub_url):
	"""Invoke REST request with verb GET to the mapi service.

	Parameters
	----------
	sub_url : string
		Sub url to be added to mapi_base_url (including the query parameters if needed)

	Returns
	-------
	object
		The result of the REST request converted from json

	Raises
	------
	Exception
		Sent by the server (in case of status code 500). The exception contains a json object with the server description
	Exception
		Sent when the status code is different from 200.
	Exception
		Sent when format is wrong
	"""
	return self.invoke_web_request(sub_url)

invoke_web_post_request(sub_url)

Invoke REST request with verb POST to the mapi service.

Parameters:

  • sub_url (string) –
    Sub url to be added to mapi_base_url (including the query parameters if needed)
    

Returns:

  • object

    The result of the REST request converted from json

Raises:

  • Exception

    Sent by the server (in case of status code 500). The exception contains a json object with the server description

  • Exception

    Sent when the status code is different from 200.

  • Exception

    Sent when format is wrong

Source code in restmapi\restmapi\services.py
def invoke_web_post_request(self, sub_url):
	"""Invoke REST request with verb POST to the mapi service.

	Parameters
	----------
	sub_url : string
		Sub url to be added to mapi_base_url (including the query parameters if needed)

	Returns
	-------
	object
		The result of the REST request converted from json

	Raises
	------
	Exception
		Sent by the server (in case of status code 500). The exception contains a json object with the server description
	Exception
		Sent when the status code is different from 200.
	Exception
		Sent when format is wrong
	"""
	return self.invoke_web_request(sub_url, "POST")

invoke_web_request(sub_url, method='Get', body=None, raw=False)

Invoke a REST request to the mapi service.

Parameters:

  • sub_url (string) –
    Sub url to be added to mapi_base_url (including the query parameters if needed)
    
  • method (string, default: 'Get' ) –
    Common REST verb (Get, Post, Delete, ...), by default "Get"
    
  • body (object, default: None ) –
    Object to be added the body, by default None
    
  • raw (bool, default: False ) –
    Define the format content, by default False. If true, the web request result is returned. Else, the body and the result are in json format and automatically parsed.
    

Returns:

  • object

    The result of the REST request converted from json if raw is False

Raises:

  • Exception

    Sent by the server (in case of status code 500). The exception contains a json object with the server description

  • Exception

    Sent when the status code is different from 200.

  • Exception

    Sent when format is wrong (only if raw is False)

Source code in restmapi\restmapi\services.py
def invoke_web_request(self, sub_url, method="Get", body=None, raw=False):
	"""Invoke a REST request to the mapi service.

	Parameters
	----------
	sub_url : string
		Sub url to be added to mapi_base_url (including the query parameters if needed)
	method : string, optional
		Common REST verb (Get, Post, Delete, ...), by default "Get"
	body : object, optional
		Object to be added the body, by default None
	raw : bool, optional
		Define the format content, by default False. If true, the web request result is returned. Else, the body and the result are in json format and automatically parsed.

	Returns
	-------
	object
		The result of the REST request converted from json if raw is False

	Raises
	------
	Exception
		Sent by the server (in case of status code 500). The exception contains a json object with the server description
	Exception
		Sent when the status code is different from 200.
	Exception
		Sent when format is wrong (only if raw is False)
	"""
	url = f"{self._mapi_base_url}/{sub_url}".rstrip("/")

	if body is not None:
		if raw:
			res = requests.request(method, url, data=body)
		else:
			res = requests.request(method, url, json=body, headers={"Content-Type": "application/json"})
	else:
		res = requests.request(method, url)
	if  not raw and res.status_code == 500 and res.headers.get("Content-Type") and "json" in res.headers.get("Content-Type"):
		raise Exception(res.json())
	if res.status_code != 200:
		raise Exception(f"invoke_web_request on {url} error:status = {res.status_code}") 
	if not raw and res.headers.get("Content-Type") and "json" not in res.headers.get("Content-Type"):
		raise Exception(f"invoke_web_request on {url} error: bad content type = {res.headers.get('Content-Type')}")		
	if raw:
		return res
	else:
		if res.text == None or res.text == "":
			return None				
		return res.json()