I have a curl request with is giving expected output :
curl -H "Authorization: Token 519dde16245438025cccb526bxxx9f3e8ce88289" --form "user=47" --form "language=HI" --form "audio_file=#/home/rishabh/Desktop/liv/audio_1.wav" --form "transcribe=1" https://dev.liv.ai/liv_speech_api/recordings/
But when I do the same using python script I am getting error
Please see the code below :
def get_app_session_id():
headers = {'Authorization' : 'Token 519dde16245438025cccb526bdxxxx3e8ce88289'}
data = {'user' : '47', 'language' : 'HI', 'transcribe':'1'}
files = {'audio_file' : open('audio_1.wav')}
url = 'https://dev.liv.ai/liv_speech_api/recordings/'
res = requests.post(url, headers = headers
, data = data, files = files)
return res
Let me know how to resolve this issue
201 means : The request has been fulfilled, resulting in the creation of a new resource
Related
curl -X PATCH -H "vmware-api-session-id: b00db39f948d13ea1e59b4d6fce56389" -H "Content-Type: application/json" -d '{"spec":{"cores_per_socket":0,"count":0,"hot_add_enabled":false,"hot_remove_enabled":false}}' https://{api_host}/rest/vcenter/vm/{vm}/hardware/cpu
I have the code for session id and URL , I need to map the code for -d part where inputs are to be provided like cpu count and all.
This should do it, so long as you're running on Java 11+
import groovy.json.JsonOutput
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
def body = [
spec: [
cores_per_socket : 0,
count : 0,
hot_add_enabled : false,
hot_remove_enabled: false
]
]
def payload = HttpRequest.BodyPublishers.ofString(JsonOutput.toJson(body))
HttpClient httpClient = HttpClient.newHttpClient()
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://{api_host}/rest/vcenter/vm/{vm}/hardware/cpu"))
.method("PATCH", payload)
.header("Content-Type", "application/json")
.header("vmware-api-session-id", "b00db39f948d13ea1e59b4d6fce56389")
.build();
HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
println response.body()
I want to upload a file via Python requests. I have successful tries with Postman and Curl. On successful response, I get the file id, but using requests i get status code 200 and empty json.
Curl example:
curl --location --request POST 'http://someurl.com/api/file' \
--header 'Content-Type: multipart/form-data' \
--header 'Accept: application/json' \
--header 'Authorization: Basic TWFsZWtzZXkubHVraW55a2hfdGVzdDE6UWF6MVdzeEA=' \
--form 'file=#"1.png"' \
--form 'fileName="1.png"' \
--form 'fileType="image/png"'
Curl output:
{
"fileId": 328446
}
Python requests:
import requests
session = requests.session()
files = {'file': ('1.png', open('1.png', 'rb'), 'image/png',)}
response = session.post('http://someurl.com/api/file', auth=HTTPBasicAuth('my_login', 'my_password'), files=files)
print(response.json())
requests output:
{}
I also tried to attach a file through this topic, but the version of the requests is older there
Python requests doesn't upload file
Postman form-data example
API POST request Example
Found a solution. This code works
import requests
from requests.auth import HTTPBasicAuth
url = 'http://someurl.com/api/file'
payload={'fileName': '1.png', 'fileType': 'image/png'}
files= {'file': open('1.png','rb')}
response = requests.post(url, auth=HTTPBasicAuth('my_login', 'my_password'), data=payload, files=files)
print(response.json())
I try to connect to db2 on cloud via Excel Power Query.
Based on documentation this is format of curl request:
curl -X POST https://hostname.com/dbapi/v4/sql_query_export -H 'authorization: Bearer MyToken' -H 'content-type: text/csv' -d '{"command":"select * from mytable"}'
I tried to go via GUI but this gives me error
I am pretty sure I am not doing it right, but I could not even google how to pass my parameters.
Could someone please navigate how to assembly M code for this?
I tried this according to #nfgl answer
let
body = [#"command"="select * from mytable"]
,json = Json.FromValue(body)
,wc = Web.Contents("https://hostname.com/dbapi/v4/sql_query_export", [Headers=[#"content-type"="text/csv", authorization="Bearer XXX"]])
,Source = Csv.Document(wc,[Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv])
in
Source
However cannot go around credentials ui anonymously:
When I try Web API with token:
BTW, everything works with python:
import http.client
conn = http.client.HTTPSConnection("hostname.com")
payload = "{\"command\":\"select * from mytable\"}"
headers = {
'content-type': "text/csv",
'authorization': "Bearer XXX"
}
conn.request("POST", "/dbapi/v4/sql_query_export", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
You can't do it via GUI, command JSON must be in request content, and content-type is the one you send, ie JSON, open advanced editor and do something like this
let
url = "https://showcase.api.linx.twenty57.net/UnixTime/fromunixtimestamp",
body = [#"UnixTimeStamp"= 1589772280, #"Timezone"=""],
json = Json.FromValue(body),
wc = Web.Contents(url, [Headers=[#"Content-Type"="application/json"], Content=json]),
Source = Csv.Document(wc,[Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv])
in
Source
I have registered a tdameritrade developer account and got a api key.
curl -X GET --header "Authorization: " \
"https://api.tdameritrade.com/v1/marketdata/aapl/quotes?apikey=my_tda_api_key"
It can get aapl's data such as below:
{"AAPL": {"assetType":"EQUITY","assetMainType":"EQUITY","cusip":"037833100","symbol":"AAPL",
#omitted all other info
Now i want to get aapl's stock option train with curl and my api key:
curl -X GET --header "Authorization: " "https://api.tdameritrade.com/v1/marketdata/chains? \
apikey=my_tda_api_key& \
symbol=aapl&contractType=all&includeQuotes=false&strategy=single&interval=1&range=all& \
fromDate=2021-8-14&toDate=2023-8-14&expMonth=all&optionType=all"
I always get all HTTP/1.1 400 Bad Request ,tried many different arguments combination in the url ,still can't get normal response,how to fix then?
https://developer.tdameritrade.com/option-chains/apis/get/marketdata/chains#
import requests
import json
td_consumer_key = "xxxxxxxxxxxxxxxxxxxxxx"
base_url = 'https://api.tdameritrade.com/v1/marketdata/chains?\
&symbol={stock_ticker}&contractType={contract_type}\
&strike={strike}&fromDate={date}&toDate={date}'
endpoint = base_url.format(stock_ticker = 'AAPL',
contract_type = 'PUT',
strike = 125,
date='2021-08-27')
page = requests.get(url=endpoint,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)
I am trying to do a POST request on my flutter application using the Http package. I tested my request first on the Api sandbox website, and then in Postman. It works well there, but once in Flutter, I always get a 400 Bad Request.
Here is my code in Flutter:
import 'package:http/http.dart';
import 'package:uuid/uuid.dart';
import 'package:wave_app/env/secrets.dart';
import 'package:wave_app/models/momo_token.dart';
String url = "https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay";
var uuid = Uuid();
String requestId = uuid.v4();
MomoToken token = await _createMomoNewTokenCollection();
String auth = "Bearer " + token.accessToken;
Map<String, String> headers = {
"Authorization": auth,
"X-Target-Environment": "sandbox",
"X-Reference-Id": requestId,
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": momoCollectionSubscriptionKey
};
String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';
Response response = await post(url, headers: headers, body: jsonBody);
int statusCode = response.statusCode;
print("STATUS CODE REQUEST TO PAY " + statusCode.toString());
print(response.reasonPhrase.toString());
print(response.body.toString());
if (statusCode == 202) {
return response.body.toString();
} else {
return null;
}
}
The api doc is here: https://momodeveloper.mtn.com/docs/services/collection/operations/requesttopay-POST?
And here is the code in curl of my Postman request (using the same variable above requestId, auth, momoCollectionSubscriptionKey)
curl --request POST \
--url https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay \
--header 'Accept: */*' \
--header 'Accept-Encoding: gzip, deflate' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSMjU2In0.eyJjbGllbnRJZCI6IjFmY2MzMjBhLTM0NWQtMTFlYS04NTBkLTJlNzI4Y2U4ODEyNSIsImV4cGlyZXMiOiIyMDIwLTAxLTExVDE1OjU3OjE4Ljc3NyIsInNlc3Npb25JZCI6ImZmYzc1OGE2LTM2MWEtNDM4ZS1hYjE5LWQ1ZGQ4ZmU4ZjEyOSJ9.DeoJyU6Hb0he_or1XeBxW-6s-xwdtmi0cUrYjQe0Z796bIGvvT-VJ214JaZItG-CBQpgv7dHbLfXNqr8D05Q7U9XiOtpr8mtYWQlY-MseGIHAyxp1qBuQkwjmBYBlDxQOYYfzG9SZ8tGFUI1_k59LMNYIhDlXXKa68Ym1sylZ8wfWjGuHaKVzMEH25ubiBwCLev5IHPchuF3toVP99U-HC8t95E3zrEt9dHgzn0hnwvpB31wcsu_b3vb-YZ1idHgosPc2GmKFsDruX14VniKBicCsnGHqZAkSPXwaOR6SIn4JZEEwhAIj3Oe2H5dwxloiX5rzaApdkwEg6KSoBXk8A' \
--header 'Cache-Control: no-cache' \
--header 'Connection: keep-alive' \
--header 'Content-Length: 194' \
--header 'Content-Type: application/json' \
--header 'Host: sandbox.momodeveloper.mtn.com' \
--header 'Ocp-Apim-Subscription-Key: 281eb****************' \
--header 'Postman-Token: ece19062-1f0b-4873-a3ed-1bd4ada8746a,528004b2-410d-4653-9909-5197a3dc95db' \
--header 'User-Agent: PostmanRuntime/7.20.1' \
--header 'X-Reference-Id: 062f8aad-f529-4d0a-804c-affb888c2b8b' \
--header 'X-Target-Environment: sandbox' \
--header 'cache-control: no-cache' \
--data '{\r\n "amount": "5",\r\n "currency": "EUR",\r\n "externalId": "123",\r\n "payer": {\r\n "partyIdType": "MSISDN",\r\n "partyId": "46733123454"\r\n },\r\n "payerMessage": "hi",\r\n "payeeNote": "hi"\r\n}'
On postman and their website, I always get a 202 Accepted response.
I am not sure, what I'm doing wrong here. Any help would be greatly appreciated!
------------ EDIT -------------------
I also tried with HttpClient, here is the code, but still got 400 Bad Request
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set("Authorization", "Bearer " + token.accessToken);
request.headers.set('content-type', 'application/json');
request.headers.set("X-Target-Environment", "sandbox");
request.headers.set("X-Reference-Id", requestId);
request.headers.set("Ocp-Apim-Subscription-Key", momoCollectionSubscriptionKey);
request.add(utf8.encode(jsonBody));
HttpClientResponse response = await request.close();
print("STATUS CODE " + response.statusCode.toString() + " " + response.reasonPhrase);
String reply = await response.transform(utf8.decoder).join();
print("REPLY " + reply);
httpClient.close();
This is definitely a problem with the server. The two headers X-Reference-Id and X-Target-Environment are being handled case sensitively by the server (i.e. it is not in compliance with the RFC).
It's Dart's io.HttpClient that forces headers to lower case, so this affects package:http and package:dio which both rely on it. There's a request to allow the client to preserve the case of headers but it's coming slowly as it's a breaking change.
In the meantime, try using this fork of the client which preserves header case. https://pub.dev/packages/alt_http/
Solved same issue by changing jsonBody from String into Map.
String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';
Only solved when changed from String -> Map;
Map jsonBody = {"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"};
and additionally, included the jsonEncode
Response response = await post(url, headers: headers, body: jsonEncode(jsonBody));
jsonEncode requires the import of Convert library
import 'dart:convert';