Response error 500 when sending post request - python-3.x

I am trying to get the table contents of website Trading Statistics to analyze it. So I used python requests library in order to send a post request as the web page is a form. Using Mozila's Inspect feature I get post data and headers request data and request url. But I get an internal error from server and contents which are in the format of a json file is not shown. Here I included the code and the error. I don't know the reason I get this error and how to change my code to get the true contents.
import requests
import json
url='http://en.ime.co.ir/subsystems/ime/services/home/imedata.asmx/GetAmareMoamelatList'
headers={"Host": "en.ime.co.ir",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0",
"Accept": "text/plain, */*; q=0.01",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Content-Type": "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest",
"Content-Length": "119",
"Origin": "http://en.ime.co.ir",
"Connection": "keep-alive",
"Referer": "http://en.ime.co.ir/spot-trading-statistics.html",
"Cookie": "ASP.NET_SessionId=jh5e35r25o0mmlvvdotwsr2t; SiteBikeLoadBanacer=e565cf8d0d6f8936cafc1b4ba323aebc71ac38c59885ac721a10cf66fd62c302; AmareMoamelatGridTblsaveId.bs.table.columns=[0,1,2,3,4,5,7,8,9,10,11,12,15,17,20,21]"}
data={'fari':'false',
'GregorianFromDate':'2021/12/18',
'GregorianToDate':'2021/12/18',
'MainCat':'0',
'Cat':'0',
'SubCat':'0',
'Producer':'0'}
req=requests.post(url, verify=True,data=data,headers=headers)
print(req):
"<Response [500]>"
print(req.content):
"b'The page cannot be displayed because an internal server error has occurred.'"

The problem here is that the server only accepts valid JSON data.
Here's what you can do.
import requests
import json
url = "https://en.ime.co.ir/subsystems/ime/services/home/imedata.asmx/GetAmareMoamelatList"
# Minimal headers will do
headers = {
"accept": "text/plain, */*; q=0.01",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/json; charset=UTF-8"
}
# Setup your body data here
payload = {
"Language": "1",
"fari": "false",
"GregorianFromDate": "2021/12/18",
"GregorianToDate": "2021/12/18",
"MainCat": "0",
"Cat": "0",
"SubCat": "0",
"Producer": "0"
}
# Convert the dict into a json string
payload_json = json.dumps(payload)
req = requests.post(url, verify=True, data=payload_json, headers=headers)
print(req.content)
Explanation
Why minimal headers will do the job fine?
A: Thanks to urllib3, usually Requests will auto config the headers for you, but not limited to
accept
accept-encoding
connection
content-length
host
user-agent
In this case, some headers aren't really that important because you're sending your HTTP requests to an API endpoint.
The header you need to care here is content-type. Setting it wrongly will cause problems.
To ensure that the destination server understood that you're trying to send a JSON body not a RAW body. You need to set the header "content-type": "application/json; charset=UTF-8"
Why was converting dict to json object string necessary?
A: You must encode your dict into a valid json string so that the server can process the data.
Here, let's see how the data looks like.
import json
#################
""" The server will definitely accept this. """
data = {
"Work" : "true",
"Sleep" : "false"
}
# Convert python dict into JSON string
data_json = json.dumps(data)
# It prints '{"Work": "true", "Sleep": "false"}'
print(repr(data_json))
#################
""" Most server should accept JSON string like this too, it's still valid. """
data = '{ \
"Work" : "true", \
"Sleep" : "false" \
}'
# It prints '{ "Work" : "true", "Sleep" : "false" }'
print(repr(data))
#################
""" The server will NOT accept this, this ISN'T valid. """
data = {
"Work" : "true",
"Sleep" : "false"
}
# It prints {'Work': 'true', 'Sleep': 'false'}
# Notice that it's missing quotation mark at start and end.
print(repr(data))

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

Logic App HTTP Trigger JSON response null value in variable

I created a logic app to get data when I trigger the logic app URI from external application. I am getting http response as expected into the logic app. As next step I am parsing JSON to get the values for specific items ("e.g. Table1") and pass into a variable. However, I get as null value into the variable
Below is the output of Logic app run where you can see the null value. Unable to find the root cause...
Http Trigger
Body:
{
"headers": {
"Connection": "close",
"Accept": "application/json",
"Accept-Encoding": "br,gzip,deflate",
"Accept-Language": "en-GB,en; q=0.9",
"Host": "prod-56.eastus2.logic.azure.com",
"Referer": "http://localhost:3000/",
"User-Agent": "Mozilla/5.0,(Macintosh; Intel Mac OS X 10_15_7),AppleWebKit/537.36,(KHTML, like Gecko),Chrome/86.0.4240.183,Safari/537.36",
"origin": "http://localhost:3000",
"sec-fetch-site": "cross-site",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"Content-Length": "125",
"Content-Type": "application/json"
},
"body": {
"studyName": "S",
"studyDescription": "DD",
"Table1": "/csdm/table1.csv",
"Table2": "/csdm/table2.csv",
"Table3": "/csdm/table3.csv"
}
}
I had the same problem. The reason was the wrong schema in the Parse JSON step. I also followed the Logic app read property of json stored in variable link. What I did was, I created a variable of the Object type called JSON_content and I placed the 'body' from the Logic App HTTP request trigger as the value. Then I added the Parse JSON action with the Content = JSON_content variable. Important thing was, that I used the input schema from the JSON_Content variable for the Parse JSON schema (using the Use sample payload to generate schema). Then the Dynamic content of the Parse JSON step consisted of JSON names (and values), which were not null finally, which I used further in the Logic App flow.

API responds with nothing when called from a Chrome extension

My issue is that I'm trying to call this API from a chrome extension:
https://wss2.cex.uk.webuy.io/v3/boxes?q=8717418549541&firstRecord=1&count=10&sortBy=relevance
Here is the code for calling the API, taken directly from Postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://wss2.cex.uk.webuy.io/v3/boxes?q=8717418549527&firstRecord=1&count=10&sortBy=relevance",
"method": "GET",
"headers": {
"User-Agent": "PostmanRuntime/7.17.1",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Postman-Token": "32322856-4e8d-4d54-87b2-199bd6181243,bea1c3bd-b5ae-4343-870d-dd73e5c88f95",
"Host": "wss2.cex.uk.webuy.io",
"Accept-Encoding": "gzip, deflate",
"Cookie": "__cfduid=dc54a227217ab713ddd4423d047c67b5f1568818173",
"Connection": "keep-alive",
"cache-control": "no-cache"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Using the above code has worked perfectly fine for a long time now. However, since last Thursday, the API stopped giving any response whatsoever. Now the status code says 200 OK but the response tab says "This request has no response data available". Trying to log out the response gives nothing as well.
If you were to simply click on the above API link, the JSON should get shown since there is no authorization. My extension properly sends the API call and I can see the call being sent in the network tab of Developer tools.
Calling the API from Postman, etc... works fine.
Of course, all necessary permissions are set in the manifest and everything was working well until it just suddenly stopped. No errors or warnings, nothing.
Has this happened to anyone before? Any ideas?
Thanks in advance!

HTTP request / Service bus - application/x-www-form-urlencoded not supported error

I've got a really simple Logic app:
HTTP request (works as end-point web hook for Slack)
Send request from Slack (URI) to Service Bus queue
I haven't made any changes in Logic App but Send message action suddenly started reporting this error:
Decoding as string is not supported for content envelope of type
'application/x-www-form-urlencoded'.
Send message is defined like that:
"Send_message": {
"inputs": {
"body": {
"Label": "#{triggerBody()}"
},
...
I see only difference in request outputs:
BEFORE
Headers
{
"Accept": "*/*",
"User-Agent": "Slackbot,1.0,(+https://api.slack.com/robots)",
"Content-Type": "application/x-www-form-urlencoded"
...
}
Body
{
"$content-type": "application/x-www-form-urlencoded",
"$content": "dG9r..."
}
NOW
Headers
{
"Accept": "*/*",
"User-Agent": "Slackbot,1.0,(+https://api.slack.com/robots)",
"Content-Type": "application/x-www-form-urlencoded"
...
}
Body
{
"$content-type": "application/x-www-form-urlencoded",
"$content": "dG9r...",
"$formdata": [
{
"key": "token",
"value": "..."
},
{
"key": "team_id",
"value": "..."
},
{
"key": "trigger_word",
"value": "!"
},
...
]
}
$formdata is now a part of the output of Request as JSON array consisting of all query parameters.
Does anyone have any ideas? I would greatly appreciate any help to make it work again.
Edit: West Europe fixed and working
Yes, in the effort to have native support for x-www-form-urlencoded data in the runtime there was a bug that was recently released. We are rolling back and patching now. Can you send me an email so we can target your region for a fix, and share a workaround? Apologies in advance - as a general rule we never want to ship anything that will break existing logic apps. In this case adding some new metadata around form-data no longer allowed people to stringify x-www-form-urlencoded data (which is what you are doing here).

Azure Logic Apps Cannot send HTTP request for wns/raw notification

I have a small logic app which is meant to fetch data from somewhere and store it on blob. I then would like to send the URL to all devices via push notification. I wish to send the URL as a raw notification, so on the app/background task, i can do some processiong.
The problem is when i use logic app to create a http POST request to send a notification, i get a 400 error. The same header with authentication and etc, with the payload and URL works fine on a POSTMAN or REST API CLIENT. THe following are the inputs and outputs. Please help. Brain dead already.
This is the input.
{
"uri": "https://xxoppoc.servicebus.windows.net/xxopPOC/messages/?api-version=2015-01",
"method": "POST",
"headers": {
"Authorization": "SharedAccessSignature sr=sb%3a%2f%2fxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxt%2f&sig=qEnxxxxxxxxxxxx&skn=DefaultFullSharedAccessSignature",
"Content-Type": "application/octet-stream",
"ServiceBusNotification-Format": "windows",
"ServiceBusNotification-Tags": "MyTag",
"X-WNS-Type": "wns/raw"
},
"body": "Some Raw Information. Hello World"
}
This is the output:
{
"statusCode": 400,
"headers": {
"transfer-Encoding": "chunked",
"date": "Wed, 30 Mar 2016 14:10:41 GMT",
"server": "Microsoft-HTTPAPI/2.0"
},
"body": {
"$content-type": "application/xml; charset=utf-8",
"$content": "PEVycm9yPjxDb2RlPjQwMDwvQ29kZT48RGV0YWlsPlRoZSBjb250ZW50IHR5cGUgZm9yIGEgJ3ducy9yYXcnIG5vdGlmaWNhdGlvbiBtdXN0IGJlICdhcHBsaWNhdGlvbi9vY3RldC1zdHJlYW0nLlRyYWNraW5nSWQ6NTNmNjhlMGItNDc1MC00ZDRkLWJiNTAtMzJjNTBmOGIyNDk1X0czLFRpbWVTdGFtcDozLzMwLzIwMTYgMjoxMDo0MSBQTTwvRGV0YWlsPjwvRXJyb3I+"
}
}
Let me mention again, I got the authentication correct as it works on Advanced REST Client on chrome and POSTMAN. The above logic app also works if i send a wns/toast notification with xml as its content-type. I however need it to be a wns/raw notification. Please help. Thank you
EDIT/PROGRESS
Thanks to MichaelB, We figured out that the content-type is being modified. I sent the request to a different URL to look at the header. The following was observed:
Content-Type: application/octet-stream; charset=utf-8
If I use the above Content-Type on POSTMAN. It actually fails as well. So this could be 1 step. Why is Azure Logic Apps adding charset-utf-8 to the end of my content type. Can I stop it?

Resources