Untitled
unknown
plain_text
9 days ago
4.8 kB
3
Indexable
Never
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Optional, List import requests app = FastAPI() ## Hard-coded configuration values AUTH_URL = "" TENANT_URL = "" USERNAME = "" PASSWORD = "" AUTHORIZATION_CODE = "" # Base64 encoded # Define the model representing the fields class MDMFields(BaseModel): displayName: Optional[str] = None therapeuticArea: Optional[str] = None groupStatus: Optional[str] = None pGJNFLAG: Optional[str] = None uri: Optional[str] = None displayName_product: Optional[str] = None groupType: Optional[str] = None class Config: orm_mode = True exclude_none = True # Exclude fields with None values from the output # Function to get the access token def get_access_token(): try: response = requests.post( AUTH_URL, data={ 'grant_type': 'password', 'username': USERNAME, 'password': PASSWORD }, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': AUTHORIZATION_CODE }, verify=False # Disable SSL verification for testing ) response.raise_for_status() # Check if the request was successful return response.json().get('access_token') except requests.RequestException as e: raise HTTPException(status_code=500, detail=f"Authentication error: {e}") # Function to extract the first string from an array of dictionaries def extract_string_from_dict(arr): if arr and isinstance(arr, list) and len(arr) > 0: item = arr[0] if isinstance(item, dict): return item.get('value') # Adjust based on the actual key in the dictionary return None # Python version of mapJson from Java def map_json(response_data) -> List[MDMFields]: mapped_fields = [] if response_data and 'objects' in response_data: for obj in response_data['objects']: attributes = obj.get('attributes', {}) # Create MDMFields instance and map values mdm_field = MDMFields( displayName=extract_string_from_dict(attributes.get('DisplayName', [])), displayName_product=extract_string_from_dict(attributes.get('DisplayName', [])), therapeuticArea=extract_string_from_dict(attributes.get('TherapeuticArea', [])), groupStatus=extract_string_from_dict(attributes.get('GroupStatus', [])), pGJNFLAG=extract_string_from_dict(attributes.get('pGJNFLAG', [])), groupType=extract_string_from_dict(attributes.get('GroupType', [])), uri=obj.get('uri', None) ) # If `uri` exists, trim the first 9 characters if mdm_field.uri: mdm_field.uri = mdm_field.uri[9:] # Append to the list mapped_fields.append(mdm_field) return mapped_fields # Function to make the API call def api_call(product_name: str = None, reltio_id: str = None): request_param = "equals(type,'configuration/entityTypes/ProductGroup') and equals(attributes.GroupType,'Brand')" if reltio_id: request_param += f" and contains (uri,'*{reltio_id}*')" if product_name: request_param += f" and equals(type,'configuration/entityTypes/ProductGroup') and contains(attributes.Name,'*{product_name}*')" try: access_token = get_access_token() response = requests.post( TENANT_URL, json=None, # Adjust this based on your API's requirements headers={ 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' }, params={'filter': request_param}, verify=False # Disable SSL verification for testing ) response.raise_for_status() # Check if the request was successful return response.json() except requests.RequestException as e: raise HTTPException(status_code=500, detail=str(e)) # Define the FastAPI endpoint for product search class SearchCriteria(BaseModel): product_name: Optional[str] = None reltio_id: Optional[str] = None @app.post("/api/search-products") def search_products(criteria: SearchCriteria): try: response_data = api_call(criteria.product_name, criteria.reltio_id) return [mdm_field.dict(exclude_none=True) for mdm_field in map_json(response_data)] except HTTPException as e: return {"error": str(e.detail)} except Exception as e: return {"error": str(e)}
Leave a Comment