Curl 415 Unsupported Media Type - api

I am trying to test my endpoint with curl and getting a 415:
curl -X POST "http://localhost:5001/api/countries/import" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer "$API_TOKEN \
--data #/D:/_countries.json
Response:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"0HLTFOME7T990:00000001"}
And here's my .net core endpoint:
// POST api/countries/import
[HttpPost]
[Route("[action]")]
public async Task<IActionResult> Import(IFormFile file)
{
...
}
Btw, I have no problem with this endpoint in postman although it's generated code doesn't work for me (the response is the same):
curl --location --request POST 'http://localhost:5001/api/countries/import' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {token here}' \
--form 'file=#/D:/_countries.json'
P.S. I am using Windows 10 and git bash to run the script.

Unsupported Media Type
Your action public async Task<IActionResult> Import(IFormFile file) expect IFormFile parameter, but you sepecified request header with Content-Type: application/json, which cuase this issue.
Please try to specify the header to --header 'Content-Type: multipart/form-data', like below.

This also can indicate a router problem.
Consider the following signature
[HttpGet("GetNearByPlaces")]
public async Task<IActionResult> GetNearByPlaces(double lattitude, double longitude, IEnumerable<SearchPlaceType> types = null)
The framework is trying to decide that a path could exist based on lattitude longitude and types in THIS example.
However, IEnumerable is not supported (the path could have an undetermined number of arguments like /23.4/34.5/4/4/6/4) and thus a 415 is returned.
Modify the signature as follows will fix it.
[HttpGet("GetNearByPlaces")]
public async Task<IActionResult> GetNearByPlaces([FromQuery] double lattitude, [FromQuery] double longitude, [FromQuery] IEnumerable<SearchPlaceType> types = null)
Also a '[FromBody]' attribute could fix the problem.

Related

Python requests return empty response after file upload

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())

Getting error 401 Unauthorised: Missing bearer authentication in header

API Documentation
This is the documentation for the available API endpoints, which are built around the REST architecture. All the API endpoints will return a JSON response with the standard HTTP response codes and need a Bearer Authentication via an API Key.
Base url
https://app.popify.site/api
Retrieve a user
curl --request GET \
--url 'https://app.popify.site/api/user' \
--header 'Authorization: Bearer {api_key}' \
Getting error 401: Missing bearer authentication in header, though I'm using correct api key.
If it is a JWT token you are passing, I'd suggest you to go to JWT decode and paste your encoded token to see what all information it consists. Ideally. roles and user related information is available in payload, if some of it is not enrolled or available on the authorization server, it will result in 401 Unauthorized.
curl --request GET \
--url 'https://app.popify.site/api/user' \
--header 'Authorization: Bearer {api_key}' \
wrap your authorization with quotes and do the same with bearer like this:
--url 'https://app.popify.site/api/user' \
-- header "Authorization ": "Bearer {api key} "
using fetch API:
const result = async getBalance(){
await fetch("https://foma.line.pm/balance", {
method: "get",
headers: {
"Authorization": " Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIU "
}}).then(response => response.json()).then(data => console.log(data)
)
}

How to get the stock option train data with tda-api?

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)

Segment.io HTTP API not collecting events

The documentation and help for this particular Segment.io is limited and sparse, so I hope it's OK to ask in here.
I have just set up a Segment.io workspace and a HTTP API source
Per the docs, I sent some POST requests (with Postman) to the https://api.segment.io/v1/track and https://api.segment.io/v1/page endpoints. The requests were structured like this:
curl -X POST \
https://api.segment.io/v1/track \
-H 'Accept: */*' \
-H 'Authorization: My4w3s0m3k3y' \
-H 'Cache-Control: no-cache' \
-H 'Connection: keep-alive' \
-H 'Content-Type: application/json' \
-H 'Host: api.segment.io' \
-H 'Postman-Token: 474d7fbe-15af-43d2-b629-61e15945e662,2c3d5fbe-2c09-4fe6-b7ea-a04e3221201b' \
-H 'User-Agent: PostmanRuntime/7.11.0' \
-H 'accept-encoding: gzip, deflate' \
-H 'cache-control: no-cache' \
-H 'content-length: 117' \
-d '{
"userId": "abc123",
"event": "My tests",
"properties": {
"name": "test 1"
}
}'
which all returned a 200 response and the following message:
{
"success": true
}
However, when I got to my dashboard, no events have been recorded.
The debugger is also empty
What am I missing here?
It looks like your write key isn't base64 encoded. When you encode your write key, remember to add the : at the end of it, before it's encoded.
Also, for the Authorization key:value, be sure to add Basic before the encoded write key. So your Authorization key:value would look like:
Authorization: Basic {encoded write key}
An example from the segment documentation:
In practice that means taking a Segment source Write Key,'abc123', as the username, adding a colon, and then the password field is left empty. After base64 encoding 'abc123:' becomes 'YWJjMTIzOg=='; and this is passed in the authorization header like so: 'Authorization: Basic YWJjMTIzOg=='.
I have been dealing with the same issue.
I found the solution as Todd said.
You should add a header Authorization: Basic + base64 encoding write key.
So, you look for the Segment source setting and get the write key.
After that, i have used an online base64 encoding tool to encode my write key.
Finally, you should add this header (Authorization) with 'Basic' and the encoded write key.
You should be able to see the tracked event in the Debugging panel in Segment web page.
I hope this helps!
You can try this code
const { promisify } = require("util");
var Analytics = require("analytics-node");
var analytics = new Analytics("xxxxxxxxxxxxxxxxxxxxxxx", {
flushAt: 1,
});
const [identify, track] = [
analytics.identify.bind(analytics),
analytics.track.bind(analytics),
].map(promisify);
console.log("user id: ", req.body.event.app_user_id);
let app_user_id = req.body.event.app_user_id;
let period_type = req.body.event.period_type;
let expiration_at_ms = req.body.event.expiration_at_ms;
let ret = "Initial";
try {
await identify({
userId: app_user_id,
traits: {
period_type: period_type,
expiration_at_ms: expiration_at_ms,
},
});
ret = "Done : Sengment done";
} catch (err) {
console.log("err: ", err);
ret = "Error : " + err;
}
return {
rafsan: ret,
};
Try to clear your browser's cache or use a different browser. I had the same problem and worked for me.
Hope this helps.

paypal authentication failure in sandbox

I encounter an issue when I try to use the Paypal sandbox API.
I've created my 2 sandbox accounts (the facilitator and the buyer), and I've created my app to get the credentials.
Then, I use the curl example provided by Paypal to get a token :
curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "my-client-id:my-secret" \
-d "grant_type=client_credentials"
I get a 200 response, with an "access_token".
Then, I use this access token to get another resource, for example :
curl -v -X GET https://api.sandbox.paypal.com/v1/invoicing/invoices?page=3&page_size=4&total_count_required=true \
-H "Content-Type: application/json" \
-H "Authorization: Bearer the-token-received-above"
Then, I get a 401 error :
{
"name":"AUTHENTICATION_FAILURE",
"message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.",
"links":[{
"href":"https://developer.paypal.com/docs/api/overview/#error",
"rel":"information_link"
}]
}
I don't understand what I'm doing wrong, since I've followed every step decribed in the Paypal doc (at least, I think I have... probably not)
Thanks for your help
curl -v -X GET "https://api.sandbox.paypal.com/v1/invoicing/invoices?page=3&page_size=4&total_count_required=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer the-token-received-above"
Actually had this exact same issue but didn't know what was wrong with my curl. For me, the issue was I forgot to put "Bearer" in the Authorization section.
For this, you are required to wrap the URL with quotation marks.
After get access_token. Please try this
try {
$params = array('access_token' => $jsonResponse->access_token);
$userInfo = OpenIdUserinfo::getUserinfo($params, $this->_api_context);
} catch (Exception $ex) {
ResultPrinter::printError("User Information", "User Info", null, $params, $ex);
exit(1);
}
ResultPrinter::printResult("User Information", "User Info", $userInfo->getUserId(), $params, $userInfo);
Don't forget to add
use PayPal\Api\OpenIdTokeninfo;
use PayPal\Api\OpenIdUserinfo;
That's worked for me.