I’m trying to use a cloudflare worker (Pasted below) to send an SMS message via the Twilio API. The CURL request (also pasted below) I’m basing the worker off of works.
Based on the 400 error from the worker the message body isn’t passed in correctly
{"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}
but the code looks fine to me. We can at least confirm the header is passed correctly because messing with the authorization value changes the error.
I also looked at the example POST request in the template gallery and can’t see a reason for the failure.
https://developers.cloudflare.com/workers/templates/pages/post_json/
What do i need to change in my worker code to make the POST request work?
Note: i recognize i shouldn’t put the Twilio Auth token in the body but I’ll rotate the key later.
async function handleRequest(request) {
const init = {
body: JSON.stringify(body),
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': "Basic " + btoa('[account id]:[Authtoken]'),
},
}
return await fetch(url, init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
})
const url = 'https://api.twilio.com/2010-04-01/Accounts/[Account id]/Messages.json'
const body = {
Body:"Hello World",
From:"+[some number]",
To:"+[some number]]",
}
curl 'https://api.twilio.com/2010-04-01/Accounts/[Account id]/Messages.json' -X POST \
--data-urlencode 'To=+[some number]' \
--data-urlencode 'From=+[some number]' \
--data-urlencode 'Body=Hello World' \
-u [account id]:[auth token]
because Twilio requires application/x-www-form-urlencoded.
REST API: Your Request
Creating or updating a resource involves performing an HTTP PUT or
HTTP POST to a resource URI. In the PUT or POST, you represent the
properties of the object you wish to update as form urlencoded
key/value pairs. Don't worry, this is already the way browsers encode
POSTs by default. But be sure to set the HTTP Content-Type header to
"application/x-www-form-urlencoded" for your requests if you are
writing your own client.
Related
I wanted to make an API call to get the parent message of a thread using the thread ID on zapier
This is the code I got by chatgpt to do that, I am getting a no output error and I am not sure why it happens
import requests
def main(input_data):
# Set the API endpoint, headers, and Slack API token for the request
api_endpoint = "https://slack.com/api/conversations.replies"
headers = {
"Authorization": "Bearer xoxb-3482548707638-4570295651095-8J4mDrROrcYV0U3L5FZhJtTf",
"Content-Type": "application/json; charset=utf-8"
}
slack_api_token = "xoxb-3482548707638-4570295651095-8J4mDrROrcYV0U3L5FZhJtTf"
# Set the request parameters
params = {
"channel": input_data["thread_id"],
"ts": input_data["thread_id"],
"inclusive": "true",
"limit": 1
}
# Make a GET request to the API endpoint
response = requests.get(api_endpoint, headers=headers, params=params)
# Get the first message in the result
message = response.json()["messages"][0]
# Print the message text to the console
print(message["text"])
This my first time working with API's or code, so I am pretty sure I mus have done something stupid. Could anyone point out what I did wrong
PS: After this, what should I learn to operate such codes, I find this interesting
Both GET and POST methods supported by the endpoint. The POST method is recommended to call endpoint with a huge number of user ids to follow, because the GET method will lead to an oversized URL that the server can't handle. How the "follow" parameter can be passed in the body of the request?
UPD: here is what I've already tried using Insomnia (the URL is always 'https://stream.twitter.com/1.1/statuses/filter.json' and the method is always 'POST' and the server response is always "No filter parameters found. Expect at least one parameter: follow track locations"):
A plain text body with Content-Type: text/html
follow=2731236345
A json body with Content-Type: application/json
{
"follow": "2731236345"
}
Another json body
{
"follow": [
2731236345
]
}
However, when I use form-url-encoded with field "follow" and the value "2731236345" I receive the response "Unauthorized".
First of all, consider looking at the Twitter Developer Labs new endpoint, because this existing API will be retired, likely (but not yet confirmed) in 2020.
When you say "without any success", what libraries are you using, and at what levels of query parameters - you're not being very clear about what is not working here. 5000 user IDs is very large. Can you please be more specific about the errors you're seeing, and the code you're trying to run?
I've managed to connect using curl:
curl --request POST \
--url 'https://stream.twitter.com/1.1/statuses/filter.json' \
--header 'authorization: <censored>' \
--data 'follow=2731236345'
The same request doesn't work in Insomnia for some reason, but it doesn't matter for the goal of this post.
I can not figure out what I'm doing wrong. I'm developing an App for BigCommerce and can not get the simple oAuth exchange to work correctly.
The initial get request is being made to https://www.my-app.com/oauth/bigcommerce/auth. This is the code in the controller for that request. It's a Laravel 5.6 app:
use Illuminate\Http\Request;
use Bigcommerce\Api\Client as Bigcommerce;
class BigcommerceOAuthController extends Controller
{
public function auth(Request $request)
{
$object = new \stdClass();
$object->client_id = 'my-client-id';
$object->client_secret = 'my-client-secret';
$object->redirect_uri = 'https://my-app.com/oauth/bigcommerce/auth';
$object->code = $request->get('code');
$object->context = $request->get('context');
$object->scope = $request->get('scope');
$authTokenResponse = Bigcommerce::getAuthToken($object);
$storeHash = str_replace('stores/', '', $request->get('context'));
Bigcommerce::configure(array(
'client_id' => 'my-client-id',
'auth_token' => $authTokenResponse->access_token,
'store_hash' => $storeHash
));
echo "<pre>";
print_r($authTokenResponse);
print_r(Bigcommerce::getTime());
echo "</pre>";
}
}
Every time I try to install my draft app from the BigCommerce control panel, I get an error because $authTokenResponse is not an object. When I debug further into the Bigcommerce\Api\Connection class, I can see that the response from the server is empty, and the status is a 401, which means "Unauthorized".
I can't figure out why I am getting this error. As far as I can see, I'm doing everything right. I've tried urlencoding the string retrieved from $request->get('scope'), since that string becomes unencoded by Laravel, but that didn't seem to help.
I am also confused how this is even supposed to work at all. In the BigCommerce docs, they show this example POST request, which uses application/x-www-form-urlencoded Content-Type and passes the request body as a url encoded string:
POST /oauth2/token HTTP/1.1 Host: login.bigcommerce.com Content-Type:
application/x-www-form-urlencoded Content-Length: 186
client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&code=qr6h3thvbvag2ffq&scope=store_v2_orders&grant_type=authorization_code&redirect_uri=https://app.example.com/oauth&context=stores/{STORE_HASH}
However, if you inspect what's going on in the Connection class, you can see that the Content-Type is being set to application/x-www-form-urlencoded as the docs say, but the request body is being passed in as a json string, not a url string. Shouldn't the request be a url encoded string as the docs suggest?
A couple of things here to check:
Do you have a public URL where you can receive the Auth Callback?
If so, did the store owner registered the app successfully? https://developer.bigcommerce.com/api/registration
When you have the client_id and secret_id. You should have all of the details needed to send a POST request to the BC Auth Token Service at https://login.bigcommerce.com/oauth2/token
The content uses URL encode Make sure to URL encode your content. Be careful of of the encoding of & and = signs when those are actually being used as separators.
More details can be found in this post:
Can BigCommerce Private Apps use OAuth
I am trying to get the file contents on Box through their API in Swift.
curl -L https://api.box.com/2.0/files/file_id/content -H "Authorization: Bearer access_token"
returns the right contents, but
curl https://api.box.com/2.0/files/file_id/content -H "Authorization: Bearer access_token"
does not.
So the "-L" part seems to be critical.
So far I have
let headers = [
"grant_type": "client_credentials",
"Authorization": "Bearer \(token)",
"scope": "public"
]
Alamofire.request("https://api.box.com/2.0/files/file_id/content", headers: headers).responseJSON { responseFile in
if let dataFile = responseFile.result.value {
print("JSON: \(dataFile)")
}
}
How can I add the "-L" part to this?
The overall structure should be correct since I can successfully get the metadata for the file by removing "/content" from the url.
According to curl manual -L/--location argument means
If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place.
So, I guess, you must check response statusCode and if it will be 3xx you need to handle redirects. Check Alamofire framework documentation about that.
Also good to read about fundamentals Handling Redirects and Other Request Changes
Based on a-a-m's answer, I got it working with the following code.
Note that I used responseString instead of responseJSON for the second request since the response was in a file format rather than in JSON format.
Alamofire.request("https://api.box.com/2.0/files/\(file_id)/content", headers: headers).responseJSON { responseFile in
if let newUrl = responseFile.response?.url {
print("new link: \(newUrl)")
//make another request using the redirection url
Alamofire.request(newUrl).responseString { content in
let filecontent = content.result.value
print (filecontent)
self.contentText.text = filecontent
debugPrint(contents)
}
}
}
}
i have following params:
$url = "https://example.com/auth_token.json"
$clientId = "...", $secretId = "..."
$callback = "http://example"
$code = "1234" - # i've received if earlier,
$body = "grant_type=authorization_code&code=$code&redirect_uri=$callback"
My goal is to get token with code, service says :
"Send a POST request to $url, providing the Client ID and Secret Key as HTTP Basic Authorization credentials, and a post body containing grant_type=authorization_code
and get in response json with token."
I tried something like this
curl $url --verbose -d $body -X -POST
but answer is - Status :401, nonauthorized and json "Unauthorized client or authentication failed, check your credentials."
then i tried to add
-H "Authorization : Basic ...encoded value..."
and get "Bad request"
Help me please, i missed something,
thx