Consuming html/json web service - html

Does someone know how I can consume or use this testing service for sending XML signed (invoice cross control Treasury Ministry)
== STAGING / SANDBOX ==
URL API RECEPTION =
https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/
OAUTH 2.0 ACCESS TOKEN URL =
https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token
CLIENT ID = api-­stag
CLIENT SECRET = [VACIO]
SCOPE = [VACIO]
Language traduction:
VACIO = EMPTY

Very good,
Passing the json data in the url post and get method.
Is something like this.!
https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/{
"id": "50601011600310112345600100010100000000011999999999",
"date": "2016-01-01T00:00:00-0600",
"transmitter": {
"idType": "02",
"idNumber": "003101123456"
},
"receiver": {
"idType": "02",
"idNumber": "003101123456"
},
"xmlInvoice": "PD94bWwgdmVyc2lvbj0iMS4wIiA/Pg0KDQo8ZG9tYWluIHhtbG5zPSJ1cm46amJvc3M6ZG9tYWluOjQuMCI+DQogICAgPGV4dGVuc2lvbnM+DQogICAgICAgIDxleHRlbnNpb24gbW9kdWxlPSJvcmcuamJvc3MuYXMuY2x1c3RlcmluZy5pbmZpbmlzcGFuIi8+DQogICAgICAgIDxleHRlbnNpb24gbW9kdWxlPSJvcmcuamJvc3MuYXMuY2x1c3RlcmluZy5qZ3JvdXBzIi8+DQogICAgICAgIDxleHRlbnNpb24gbW9kdWxlPSJvcmcuamJvc3MuYXMuY29ubmVjdG9yIi8+DQogICAgICAgIDxleHRlbnNpb24gbW..."
}
"xmlInvoice": {
"description": "XML electronic invoice signed by the taxpayer using XAdES-EPES. The XML text must be converted to a byte array and encoded in Base64. The character map to use in XML and in Base64 encoding is UTF8.",
"type": "string"
}

Related

How to specify content type as application/json while sending message to azure service bus topic using an Azure Function? [duplicate]

This question already has answers here:
Azure Function - Python - ServiceBus Output Binding - Setting Custom Properties
(2 answers)
Closed 8 months ago.
I'm using an Azure Function (Python) to send a message to a Service Bus topic whenever a file lands in blob storage following a similar set up to that outlined here.
In particular, in order to send the message I have this in the JSON file:
{
"type": "serviceBus",
"direction": "out",
"connection": "AzureServiceBusConnectionString",
"name": "msg",
"queueName": "outqueue"
}
and in init.py file I have msg.set(input_msg) where input_msg is a JSON string, the output of doing json.dumps(list(reader)) on a CSV string.
When this message is picked up by the topic and subscriptions it has content type set to text/plain, whilst I'd like this to be application/json as mentioned here.
Is there a way to set this, for instance when I do msg.set, is there a way to specify the content type?
Full code:
init.py
def get_json_content_from_csv(csv_content: str) -> str:
reader = csv.DictReader(io.StringIO(csv_content))
json_content = json.dumps(list(reader))
return json_content
def main(event: func.EventGridEvent, msg: func.Out[str]):
data = event.get_json()
url = data["url"]
input_blob = BlobClient.from_blob_url(url, DefaultAzureCredential())
csv_content = input_blob.download_blob(encoding='UTF-8').readall()
json_content = get_json_content_from_csv(csv_content)
msg.set(json.dumps(json_content))
function.json
{
"bindings": [
{
"type": "eventGridTrigger",
"name": "event",
"direction": "in"
},
{
"type": "serviceBus",
"direction": "out",
"connection": "AzureServiceBus",
"name": "msg",
"topicName": "dev-iris-service-bus-topic"
}
]
}
According to this github issue for the Python SDK:
Cannot set Service Bus Message ContentType - Github Issue
The github issue response points to the docs here to set the contentType property on the message class
https://learn.microsoft.com/en-us/python/api/uamqp/uamqp.message.messageproperties?view=azure-python

How to test an API response for binary

Question:What is the easiest way to test an API response for a binary response?
Context:I have a function that makes an API Call for some data. The response (api_response) of that API call will either be JSON or binary. If JSON, and if it contains percent_complete then the data is not yet ready, and my function uses the percent_complete key:pair value to update a progress bar for the user. If the response is JSON and contains meta, then my data is ready and has returned as a JSON object. If the response is binary, then my data is also ready, however has been returned as .xlsx [binary]. This is the response when the data is not ready and you will see percent_complete is utilized for a progress bar -
{
"data": {
"id": "2768510",
"type": "jobs",
"attributes": {
"job_type": "PORTFOLIO_VIEW_RESULTS",
"started_at": "2022-04-14T16:19:21Z",
"parameters": {
"end_date": "2022-04-14",
"output_type": "json",
"view_id": 304078,
"portfolio_id": 1,
"portfolio_type": "firm",
"start_date": "2022-04-14"
},
"percent_complete": 0.0,
"status": "In Progress"
},
"relationships": {
"creator": {
"links": {
"self": "/v1/jobs/2768510/relationships/creator",
"related": "/v1/jobs/2768510/creator"
},
"data": {
"type": "users",
"id": "731221"
}
}
},
"links": {
"self": "/v1/jobs/2768510"
}
},
"included": []
Current function:The following function continues to call the API every 5-seconds (using the 7-digit code in self, per the above API object) until meta is returned in a JSON object (therefore my data is returned as a JSON object) and returns the JSON object as api_response.Otherwise, the API call continues every 5-seconds and simply uses percent_complete to update a status bar (using enlighten library)
def api_call():
# Calling function containing the JOBS API endpoint for calling, until its RESPONSE == data requested.
endpoint_url = endpoint_initializer()
# Calling function containing API credentials
key, secret, url, group_url = ini_reader()
# Setting variable for use in progress bar, used to reflect API 'percent_complete' key pair value.
BAR_FORMAT = u'{id_value} {percentage:3.0f}%|{bar}| ' u'[{elapsed}<{eta}, {rate:.2f} %/s]'
manager = enlighten.get_manager()
date = dt.datetime.today().strftime("%Y-%m-%d")
print("------------------------------------\n","API URL constructed for:", date, "\n------------------------------------")
print("----------------------------------------------------------------------\n","Addepar Endpoint:", endpoint_url, "\n----------------------------------------------------------------------")
# Setting variable with counter for progress bar.
pbar = manager.counter(total=100, bar_format=BAR_FORMAT)
while True:
response = requests.get(url = endpoint_url, auth = HTTPBasicAuth(key, secret), headers = {"Vendor-firm": "665"})
api_response = json.loads(response.text)
if "meta" not in api_response:
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = api_response["data"]["attributes"].get("percent_complete", '')*100
pbar.count = res2
pbar.update(incr=0, id_value=id_value)
time.sleep(5)
elif "meta" in api_response:
pbar.count = 100
pbar.update(incr=0, id_value=id_value)
pbar.close()
return api_response
How would I expand this function to test if the response (api_response) contains binary and if so, then return api_response?
A normal http-server should return an appropriate content-type. Please check:
response.headers['content-type']
Per Markus response, by accessing the Content-Type response.headers, I am able to trinagulate whether the response is binary (Content-Type: application/binary) or JSON (Content-Type: application/vnd.api+json).

Is there any documentation for EasyPost that shows the raw JSON for the requests, including headers? Or e.g. a PostMan collection?

I'm just doing the preparation for an integration with EasyPost's Shipping API, which will be server side C#, but we always build a PostMan collection for new integrations, so that we can test data separately from the application if there's an issue.
While I do love the fact that EP provide C# libraries and examples, I'm struggling to find anything that just gives me a list of required headers and the raw JSON format for the body of any requests. It feels a bit like they're just being a little too helpful.
I'll be looking at the Orders endpoint probably.
I've got an account, I've checked all their documentation and searched the internet but haven't found anything so I'm hoping I'm not the first developer to want to use a client application for testing outside my code.
Update:
EasyPost now does have a public workspace https://www.postman.com/easypost-api
with at least 1 public collection
The curl examples are basically the same as json:
For the Address creation example:
-d "address[street1]=417 MONTGOMERY ST"
is the equivalent of
{ "address": { "street1": "417 MONTGOMERY ST" } }
(you might have to escape some characters to be valid json).
Check out How to stimulate cURL request to a request using postman for postman with HTTP Basic Auth.
EasyPost does not provide a public Postman collection; however, here is an example of a shipment Postman body (raw) that could be used. You can adjust the values, actions, objects, etc to your needs.
Using the following, you shouldn't need to pass any headers. You'll pass your API key under the username field with the Basic Auth authorization type.
{
"shipment": {
"to_address": {
"id": "adr_123..."
},
"from_address": {
"id": "adr_123..."
},
"parcel": {
"id": "prcl_123..."
},
"carrier_accounts": {
"id": "ca_123..."
},
"options": {
"address_validation_level": "0"
}
},
"format": "json",
"controller": "shipments",
"action": "create"
}

JSON string pulled via net/http to Hash

I'm trying to pull JSON from a Yahoo API to get the conversion rate of USD to SEK. However, I can't seem to get the JSON converted to a Hash, it shows "query" as being the only key since JSON comes in as one string.
The JSON request returns:
{"query":{"count":1,"created":"2016-12-04T13:06:00Z","lang":"en-us","results":{"rate":{"id":"USDSEK","Name":"USD/SEK","Rate":"9.1900","Date":"12/2/2016","Time":"9:59pm","Ask":"9.2000","Bid":"9.1900"}}}}
My code is as follow:
require 'net/http'
require 'json'
url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDSEK%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback='
uri = URI(url)
response = Net::HTTP.get(uri)
json_hash= JSON.parse(response)
puts json_hash["Rate"]
the puts statement returns 'nil'
I've tried following an example from this site, however I do not yield the same results based on the way my data is being brought as his is being statically entered.
*Note I am not using 'ostruct', trying simply with json.
Thank you for any insight.
As you can see, the field you are looking for is into an inner hash. Try
puts json_hash["query"]["results"]["rate"]["Rate"]
Have you check the structure of your json?
{
"query": {
"count": 1,
"created": "2016-12-04T13:06:00Z",
"lang": "en-us",
"results": {
"rate": {
"id": "USDSEK",
"Name": "USD/SEK",
"Rate": "9.1900",
"Date": "12/2/2016",
"Time": "9:59pm",
"Ask": "9.2000",
"Bid": "9.1900"
}
}
}
}
To fetch the rate key you should do something like:
json_hash["query"]["results"]["rate"]
Compare that with json above to understand your problem.

JSON API result format

Folks,
Designing my first API in Node.JS using restify.js. My background is not webapis, pardon my amateur questions. In any case, I would like to have the res.send(data); responses to comply with the http://jsonapi.org/format/ so that my mobile application can start utilizing the api calls. At the moment if you were to call my api, it would return data in the following format:
{"Count":1,"Items":[{"dbsource":{"S":"foo"},"id":{"S":"5002820"},"name":{"S":"fnameblah,lnameblah"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Actually what you see above is just a return of a DynamoDB Query call.
So the question is... do you use a special library that you can pass data to, which would format and return the data in JSON format. Which in turn you can return it via res.send(data) to the clients, or is it up to us to make 'data' JSON compliant, then return it? At the end of the day we all want the results to look like:
{
"posts": [{
"id": "1",
"title": "Rails is Omakase",
"links": {
"author": "9",
"comments": [ "5", "12", "17", "20" ]
}
}]
}
Thanks!
In server side, stringify JSON object,
//...
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data)); //data is JSON object
res.end();
In client side, parse JSON string accordingly.
EDIT: Corrected response content type.
JSON data from server should be a JSON string
You have to parse it back the JSON format in client.
JSON.parse(string); // return JSON object