How to set request field of a BundleEntry of FHIR Model - python-3.x

I am using https://pypi.org/project/fhir.resources/ and my goal is to set request, taht is:
new_bundle_entry = BundleEntry()
patient_bundle_entry.resource = new_patient.sh_patient // as Patient
patient_bundle_entry.request = xxx
where xxx should codify :
"request": {
"method": "POST",
}
What is the class that I should use to instanciate the above and set the attribute request?
Please, any help would be very appreciated.

identif ="identifier=http://hl7.eu/fhir/ig/gk/identifier/"+pilot_id+"/patient|"+user_id
method_description = {
"method": "POST",
"url": "Patient",
"ifNoneExist": identif
}
req = BundleEntryRequest(**method_description)
p_bundle_entry.request = req

Related

Adding to a database creates a new database within page in notion

Here's my current code:
import json
import requests
def createPage(database_id, page_id, headers, url):
newPageData = {
"parent": {
"database_id": database_id,
"page_id": page_id,
},
"properties": {
"Name": {"title": {"text": "HI THERE"}},
},
}
data = json.dumps(newPageData)
res = requests.request("POST", url, headers=headers, data=data)
print(res.status_code)
print(res.text)
database_id = "ea28de8e9cca4f62b4c4da3522869d03"
page_id = "697fd88570b3420aaa928fa28d0bf230"
url = "https://api.notion.com/v1/databases/"
key = "KEY"
payload = {}
headers = {
"Authorization": f"Bearer {key}",
"accept": "application/json",
"Notion-Version": "2021-05-11",
"content-type": "application/json",
}
createPage(database_id, page_id, headers, url)
But everytime I run this, it appears like I keep getting new databases within the page. This is before running the script:
This is after running the script:
I would like it to be like this after running the script:
How can that be achieved?
It looks as you're calling the API URL that creates a new Database, and not the one that creates a new page.
This URL: https://api.notion.com/v1/databases/ is for creating new databases, and not for creating pages.
In order to create a new page within a database, use the following URL:
https://api.notion.com/v1/pages
Where you'll need to provide the previously created database id, among other identifiers
More detailed documentation can be found here
https://developers.notion.com/reference/post-page

Create a new Azure CI pipeline by invoking existing YAML file in the repository via REST API through Python script

I have an existing azure-pipelines.yml file in my branch. I want to invoke this file via Azure RestAPI and let Azure CI Pipelines create. I need to do it by python code.
something I have tried like this but getting some error related 203. It seems ...... 203 Non-Authoritative Information Return Issue when attempting to perform any action (GET/POST/etc) through the Azure DevOps API.
..Main focus is create pipelines by code. If any existing/working examples, it would be helpful..
import json
api_url = "https://dev.azure.com/DevOps/Ops/_apis/pipelines?api-version=6.0-preview.1"
json_data = {
"folder": "/",
"name": "My Pipeline",
"configuration": {
"type": "yaml",
"path": "/Boot/{{ project_name }}/pipelines/azure-pipelines.yaml",
"repository": {
"name": "Boot",
"type": "azureReposGit"
}
}
}
headers = {"Content-Type":"application/json"}
response = requests.post(api_url, data = json.dumps(json_data), headers=headers)
#print(response.json())
print(response.status_code)```
Write a Python demo for you here:
import requests
import json
def create_pipeline_basedon_yaml(Organization, Project, Repository, Yaml_File, Pipeline_Folder, Pipeline_Name, Personal_Access_Token):
##########get repo id##########
url_repoapi = "https://dev.azure.com/"+Organization+"/"+Project+"/_apis/git/repositories/"+Repository+"?api-version=4.1"
payload_repoapi={}
headers_repoapi = {
'Authorization': 'Basic '+Personal_Access_Token,
}
response_repoapi = requests.request("GET", url_repoapi, headers=headers_repoapi, data=payload_repoapi)
repo_id = response_repoapi.json()['id']
##########create pipeline##########
url_pipelineapi = "https://dev.azure.com/"+Organization+"/"+Project+"/_apis/pipelines?api-version=6.0-preview.1"
payload_pipelineapi = json.dumps({
"configuration": {
"path": Yaml_File,
"repository": {
"id": repo_id,
"type": "azureReposGit"
},
"type": "yaml"
},
"folder": Pipeline_Folder,
"name": Pipeline_Name
})
headers_pipelineapi = {
'Authorization': 'Basic '+Personal_Access_Token,
'Content-Type': 'application/json'}
requests.request("POST", url_pipelineapi, headers=headers_pipelineapi, data=payload_pipelineapi)
Organization = "xxx"
Project = "xxx"
Repository = "xxx"
Yaml_File = "xxx.yml"
Pipeline_Folder = "test_folder"
Pipeline_Name = "Pipeline_basedon_yaml"
Personal_Access_Token = "xxx"
create_pipeline_basedon_yaml(Organization, Project, Repository, Yaml_File, Pipeline_Folder, Pipeline_Name, Personal_Access_Token)
I can successfully create the pipeline based on the specific yaml file:

Python - Unable to send request [error 203, POST]

I have 4 string variables like this:
a = 'a long string'
b = 'a longer string'
c = 'a path (with a single slash \)'
d = 'another path (with a single slash \)'
I am supposed to be adding this to a variable, which is a list of dictionaries. Something like this:
var = [
{
"op": "add",
"path": "/fields/System.Title",
"from": null,
"value": a
},
{
"op": "add",
"path": "/fields/System.Description",
"from": null,
"value": b
},
{
"op": "add",
"path": "/fields/System.AreaPath",
"from": null,
"value": c
},
{
"op": "add",
"path": "/fields/System.State",
"from": null,
"value": "New"
},
{
"op": "add",
"path": "/fields/System.IterationPath",
"from": null,
"value": d
}
]
FYI, var[3] does not take the variables I created. Only var[0], var[1], var[2] and var[4]
All this works fine. As you may have guessed by now, this is my payload for a POST operation that I am supposed to be sending (it's actually to create a work item in my Azure DevOps organization with the above parameters). Please note, the from in var only accepts null.
When I use POSTMAN to send the above request, it works (except I am not passing the variables in the body, but actually the hard coded values). When I do the same using Python, on VSCode, I am always thrown a 203, which is essentially an incorrect/incomprehensible payload. I am not able to get this working.
This is essentially the code (please assume the variables):
url = f'https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/${workitemtype}?api-version=6.0'
header = {'Content-Type': 'application/json-patch+json', 'Authorization': f'Basic {PAT}'}
request = requests.post(url = url, json = var, headers = header)
I've tried everything I can think of:
request = requests.post(url = url, **data = json.dumps(var)**, headers = header),
request = requests.post(url = url, **data = json.loads(var)**, headers = header),
request = requests.post(url = url, **data = json.loads(str(var))**, headers = header) -> this because loads(var) was throwing TypeError: the JSON object must be str, bytes or bytearray, not list
I also tried to include the entire var variable as a docstring - but the problem with that is that I need to pass the variables (a, b, c and d) into it, and docstrings cannot accept them.
How may I overcome this?
I have a feeling that it's the null that's causing this issue, but I could be wrong.
I tested with your code, and i failed to pass the authorization if i defined the Authorization in the request headers. I fixed it by passing the PAT to the auth parameter in requests.post method. I made a little to your code. And it worked fine for me. See below:
import requests
if __name__ == '__main__':
a = 'a longer string'
b = 'a longer string'
c = 'project\area'
d = 'project\iteration'
var = [
{
"op": "add",
"path": "/fields/System.Title",
"from": None,
"value": a
},
{
"op": "add",
"path": "/fields/System.Description",
"from": None,
"value": b
},
{
"op": "add",
"path": "/fields/System.AreaPath",
"from": None,
"value": c
},
{
"op": "add",
"path": "/fields/System.State",
"from": None,
"value": "New"
},
{
"op": "add",
"path": "/fields/System.IterationPath",
"from": None,
"value": d
}
]
pat = "Personal access token"
url = 'https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/$Task?api-version=6.1-preview.3'
header = {'Content-Type': 'application/json-patch+json'}
request = requests.post(url = url, json = var, headers = header, auth=("", pat))
However you can also check out azure-devops-python-api. See below example code to create a work item.
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v5_1.work_item_tracking.models import JsonPatchOperation
def _create_patch_operation(op, path, value):
patch_operation = JsonPatchOperation()
patch_operation.op = op
patch_operation.path = path
patch_operation.value = value
return patch_operation
def _create_work_item_field_patch_operation(op, field, value):
path = '/fields/{field}'.format(field=field)
return _create_patch_operation(op=op, path=path, value=value)
if __name__=='__main__':
a = 'a longer string'
b = 'a longer string'
c = 'project\area'
d = 'project\iteration'
# Fill in with your personal access token and org URL
personal_access_token = 'PAT'
organization_url = 'https://dev.azure.com/{org}/'
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
# Get a client
wit_client = connection.clients.get_work_item_tracking_client()
patch_document=[]
patch_document.append(_create_work_item_field_patch_operation('add', 'System.Title', a))
patch_document.append(_create_work_item_field_patch_operation('add', 'System.Description', b))
patch_document.append(_create_work_item_field_patch_operation('add', 'System.AreaPath', c))
wit_client.create_work_item(patch_document, "Project", 'Task')

Azure Function crashes upon missing url query

I have an Azure-Function with the following configuration
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "cosmosDB",
"name": "inputDocument",
"databaseName": "MeasureInputData",
"collectionName": "hubs",
"connectionStringSetting": "measure-cosmosdb_DOCUMENTDB",
"direction": "in",
"sqlQuery": "SELECT * FROM c WHERE c.uuid = {hub}"
}
],
"disabled": false
}
As you can see above, I have the {hub} in the sqlQuery passed as a url parameter.
Doing a request like
https://<my-function-url>?code=<my-function-key>&hub=<my-hub-id>
returns the matching hub.
If leaving the value <my-hub-id> empty
https://<my-function-url>?code=<my-function-key>&hub=
returns an empty object.
The issue is when I donĀ“t provide the hub parameter in the URL the function crashes.
https://<my-function-url>?code=<my-function-key>
requesting the above returns http status code 500
Shouldn't missing query parameters be handled in some way?
Thanks
It seems the sql will be
SELECT * FROM c WHERE c.uuid =
but not
SELECT * FROM c WHERE c.uuid = "" or SELECT * FROM c WHERE c.uuid = null
when the parameter "hub" missing.
Azure function cosmos db binding will not handle the missing parameter in query. If you want to handle this error, I think we can create another api or function and put(call) the original function url in this new api/function. Then we can handle this error in the new api/function.
If you hope azure function to add this feature, you can raise your idea to the azure function feedback page.
No, you should handled that. If you check the hello world sample:
[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
It tries to read value from query string and from body. In case it's null, it will return
new BadRequestObjectResult("Please pass a name on the query string or in the request body")
so you should do the same, in case there's no hub provided in the querystring, return 400 (bad request)

amazon product advertising api node js sdk request throtteling issue

I am getting this error in response when calling amazon product advertising api from nodejs sdk.
Error calling PA-API 5.0!
Printing Full Error Object:
{
"status": 429,
"response": {
"req": {
"method": "POST",
"url": "https://webservices.amazon.com/paapi5/getitems",
"data": {
"ItemIds": [
"B075LRK2QK"
],
"PartnerTag": "raassnabct-21",
"PartnerType": "Associates",
"Condition": "New",
"Resources": [
"Images.Primary.Medium"
]
},
"headers": {
"user-agent": "paapi5-nodejs-sdk/1.0.0",
"authorization": "AWS4-HMAC-SHA256 Credential=MY_KEY/20191215/us-east-1/ProductAdvertisingAPI/aws4_request, SignedHeaders=content-encoding;content-type;host;x-amz-date;x-amz-target, Signature=030b9f07a2336302a6d8855e216e602589960bf919dc9e700daac6155dcce1a2",
"content-encoding": "amz-1.0",
"content-type": "application/json; charset=utf-8",
"host": "webservices.amazon.com",
"x-amz-target": "com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems",
"x-amz-date": "20191215T111055Z",
"accept": "application/json"
}
},
"header": {
"server": "Server",
"date": "Sun, 15 Dec 2019 11:10:54 GMT",
"content-type": "application/json",
"content-length": "193",
"connection": "close",
"x-amzn-requestid": "0ada8ea0-944f-47a2-bbef-acc0f5d984a9",
"vary": "Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent",
"content-encoding": "gzip",
"x-amz-rid": "JTD0DAVWEB1CMXK1F5BW"
},
"status": 429,
"text": "{\"__type\":\"com.amazon.paapi5#TooManyRequestsException\",\"Errors\":[{\"Code\":\"TooManyRequests\",\"Message\":\"The request was denied due to request throttling. Please verify the number of requests made per second to the Amazon Product Advertising API.\"}]}"
}
}
Status Code: 429
Error Object: "{\"__type\":\"com.amazon.paapi5#TooManyRequestsException\",\"Errors\":[{\"Code\":\"TooManyRequests\",\"Message\":\"The request was denied due to request throttling. Please verify the number of requests made per second to the Amazon Product Advertising API.\"}]}"
And the code is
var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = 'accessKey';
defaultClient.secretKey = 'secretKey';
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
getItemsRequest['PartnerTag'] = 'raassnacbt-21';
getItemsRequest['PartnerType'] = 'Associates';
getItemsRequest['ItemIds'] = ['B075LRK2QK'];
getItemsRequest['Condition'] = 'New';
getItemsRequest['Resources'] = ['Images.Primary.Medium', 'ItemInfo.Title', 'Offers.Listings.Price'];
function parseResponse(itemsResponseList) {
var mappedResponse = {};
for (var i in itemsResponseList) {
mappedResponse[itemsResponseList[i]['ASIN']] = itemsResponseList[i];
}
return mappedResponse;
}
try {
api.getItems(getItemsRequest, callback);
} catch (ex) {
console.log("Exception: " + ex);
}
I am getting "too many requests" error even when making just one. also tried to run this on server just in case it had something to do with localhost. there is no manual modification, it is just the sdk code with my credentials. any idea what might be the issue?
This is a very common problem people face while using Amazon product API. Amazon works on a very different algorithm. It allocates API threshold/ usage limit based on the commission you have earned through amazon. Once your allocated limit is exhausted, you will receive such errors.
To fix this, ask your friend to buy through your affiliate link. You will get some threshold.
Old topic, but maybe can be useful. I realized this error is also shown when authentication failed. So it is necessary to take into account that associate IDs are only active in a concrete region and also that new generated API Keys can take until 72h to be really active, so check these points if necessary apart from the quota stuff the other users mentioned.

Resources