Forming a request.post from a curl on python - python

I have a small project i need a tempmail for, so i found this site https://mail.tm/en, so i was trying to acess the post via the api and instructions given here https://api.mail.tm/.
As I am new at working with curl and so on I have a lot of problems authorizing into an account there.
First of all i got an CURL link on site like this one:
curl -X POST "https://api.mail.tm/accounts" -H "accept: application/ld+json" -H "Authorization: testing" -H "Content-Type: application/ld+json" -d "{\"address\":\"test\",\"password\":\"stackoverflow\"}"
I tried to form it all in a post request, so i did this
headers = {"accept": "application/ld+json", "Authorization": "header", "Content-Type": "application/ld+json"}
data = "{\"address\":\"zashyganii\",\"password\":\"chertila\"}"
mail = requests.post("https://api.mail.tm/accounts", data = data, headers = headers)
print(mail.status_code)
the error code is 400, noted on the api site like this.
400 Error:
Response body
Download
{
"#context": "/contexts/ConstraintViolationList",
"#type": "ConstraintViolationList",
"hydra:title": "An error occurred",
"hydra:description": "address: This value is not a valid email address.\naddress: The domain \"\" is not valid.",
"violations": [
{
"propertyPath": "address",
"message": "This value is not a valid email address."
},
{
"propertyPath": "address",
"message": "The domain \"\" is not valid."
}
]
}
Could you please turn this curl in to a request.post on python so it will work for this api

Seems like there are not any problem with the request. It's a validation fail.

Related

How to send a text message with Whatsapp Cloud API

I'm having troubles using Whatsapp Cloud API (which was released to the public on May 22). I did everything in the getting started in "Set up Developer Assets and Platform Access" section, that way I was able to send the template hello world in Ubuntu 20.04.4 LTS with:
curl -i -X POST \
https://graph.facebook.com/v14.0/my_number/messages \
-H 'Authorization: Bearer my_token' \
-H 'Content-Type: application/json' \
-d '{ "messaging_product": "whatsapp",
"to": "my_reciever",
"type": "template",
"template": { "name": "hello_world", "language": { "code": "en_US" } }
}'
or with Python 3.10 and requests 2.27.1 with:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "template",
"template": {"name": "hello_world", "language": {"code": "en_US"}}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
Then, I tried to send a text message with this:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "text",
"text": {
"preview_url": "false",
"body": "MESSAGE_CONTENT"
}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
And, even though the response is correct, something like this:
{'messaging_product': 'whatsapp', 'contacts': [{'input': 'my_reciever', 'wa_id': 'my_reciever'}], 'messages': [{'id': 'wamid.HBgMNTchangingMDYyM0I2AA=='}]}
I don't recieve any message in my_reciver. I don't know what I'm doing wrong, I might have to configure the webhook for this to work? Do I need to opt-in before recieve the message (this can be read in get-started page)?
I even tried using some unofficial wrappers in python like heyoo, but I got the same result.
Hope someone can help me with this, thanks.
Note: this is a similar post, but that one is with node, not Python or Curl, so I guess this does not count as repost.
I have written a brief article on WhatsApp Cloud API like how to send and receive WhatsApp messages and also set up a never expiry access token. Please have a look WhatsApp Cloud API
You need to send the WhatsApp message from your personal number to your WhatsApp business number after that you can send the message from your business number to your personal number. Basically, WhatsApp has a template message concept within 24h session and according to your question, I think you are trying to send a normal unsession message from a business number to your personal number. So, to avoid this case you need to first message from your personal to your business number then you can receive the message to your personal number. Full details in the article regarding template message.
Here is the CURL request for normal message
curl --location --request POST 'https://graph.facebook.com/v13.0/<Your Phone number ID>/messages' \
--header 'Authorization: Bearer <Your Temporary access token>' \
--header 'Content-Type: application/json' \
--data-raw '{"messaging_product":"whatsapp","recipient_type":"individual",
"to":"918587808915","type":"text","text": {"body":"Hello Rishabh!"}
}'
The official META-whatsapp documentation indicates that in order to send such messages, the conversation must be initiated by the user. https://developers.facebook.com/docs/whatsapp/conversation-types

PYTHON: requests.post() how to send request_body encoded as application/x-www-form-urlencoded

I'm doign an app with the Spotify API. My problem is I'm trying to get an access_token but It's not working. In the docs it says i need to send the body encoded as application/x-www-form-urlencoded so I search a little bit and It should work just setting request_body as a dictionary.
This is the code of my function:
def get_access_token(self):
auth_code, code_verifier = self.get_auth_code()
endpoint = "https://accounts.spotify.com/api/token"
# as docs said data should be encoded as application/x-www-form-urlencoded
# as internet says i just need to send it as a dictionary. However it's not working
request_body = {
"client_id": f"{self.client_ID}",
"grant_type": "authorization_code",
"code": f"{auth_code}",
"redirect_uri": f"{self.redirect_uri}",
"code_verifier": f"{code_verifier}"
}
response = requests.post(endpoint, data=request_body)
print(response)
The response I'm getting is always <Response [400]>
Here are the docs, step 4 https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
NOTE: I tryed executing this as a curl and it works fine I'm not sure what I'm doing wrong in the python code
here's the command:
curl -d client_id={self.client_ID} -d grant_type=authorization_code -d code={auth_code} -d redirect_uri={self.redirect_uri} -d code_verifier={code_verifier} https://accounts.spotify.com/api/token
You can specify the request type in the request header.
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(endpoint, data=request_body, headers=headers)
print(response)

MSGraph subscription create error: "message": "Operation: Create; Exception: [Status Code: Unauthorized; Reason: ]", "code": "ExtensionError"

I need to create subscription to users using Microsoft Graph.
I have all rights in Aure Active Directory:
User.Read.All.
My subscription method:
def create_subscription_to_users(self):
t = datetime.utcnow() + timedelta(minutes=settings.MAX_TIME_DELTA_IN_MINUTES)
payload = {
"changeType": "updated",
"notificationUrl": "{0}/webhooks/azure".format(settings.AZURE_WEBHOOKS_CALLBACK_BASE_URL),
"resource": "users",
"expirationDateTime": t.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
}
response = self.graph_client.post(url='{0}/subscriptions'.format(settings.GRAPH_URL), json=payload).json()
self.add_log(url='{0}/subscriptions'.format(settings.GRAPH_URL),
method='POST', payload=payload, response=response)
return response
My validation class:
class AzureHook(View):
def post(self, request):
url = request.get_full_path()
parsed_url = parse_qs(urlsplit(url).query)
validation = dict(parsed_url).get('validationToken')[0]
return HttpResponse(validation.encode('utf-8'), content_type='text/plain')
But I still receive as response for creating subscription:
{"error": {"innerError": {"date": "2019-07-03T11:29:39", "request-id": "5e7f1fc3-8ef4-4511-b661-35bf7d146cc3"}, "message": "Operation: Create; Exception: [Status Code: Unauthorized; Reason: ]", "code": "ExtensionError"}}
Could someone please help me with this?
So as to get rid of this error add following scopes in the application. User.Read.All&offline_access, User.ReadWrite.All, Group.ReadWrite.All, Group.Read.All, Directory.ReadWrite.All, Directory.AccessAsUser.All, openid.
To get the authorization code try this url in your browser. https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=&response_type=code&redirect_uri= http://localhost:4200/api/auth/callback/AzureAD&response_mode=query&scope=User.Read.All &User.ReadWrite.All&Group.ReadWrite.All&Group.Read.All&Directory.ReadWrite.All&Directory.AccessAsUser.All&openid&offline_access&state=12345&prompt=login
Try this request first using postman, I am attaching curl request for your reference.
curl -X POST \
https://graph.microsoft.com/v1.0/subscriptions \
-H 'Authorization: Bearer ' \
-H 'Content-Type: application/json' \
-d '{
"changeType": "updated",
"notificationUrl": "https://5690e074.ngrok.io",
"resource": "groups",
"expirationDateTime": "2019-07-13T10:19:03.170Z",
"clientState": "secretClientValue"
}'

Requests on a api doesn't work (Curl and python)

So, I try to make a program who tell me the schedule of my bus, i take this real time information on an Api:
https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786
but when i lunch it there is an error :
"error": "Unknown dataset: tr-vianavigo"
I have a token to use I think but how ?
the Curl for this api is :
curl -X GET --header "Accept: application/json" "https://api-lab-trone-
stif.opendata.stif.info/service/tr-vianavigo/departures?
line_id=100100020%3A20&stop_point_id=59%3A4726914"
when i use the first url on my web browser it work and show me :
[
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "12"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "20"
},
{
"lineDirection": "Juvisy RER",
"code": "duration",
"time": "38"
},
{
"lineDirection": "Savigny Toulouse-Lautrec",
"code": "duration",
"time": "45"
}
]
but in python if i just test :
import requests
#my token
apikey = 'ef169369dfd911b01371b73e975ed88adce881bc92dbbd9720551c94'
#url of the api
url ='https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100385%3A385&stop_point_id=StopPoint%3A59%3A6195786'
#requests
r = requests.get(url, apikey)
print(r.text)
it make the error :
"error": "Unknown dataset: tr-vianavigo"
You must use one of your API keys for this purpose. An API key is obtained via your user account in My API keys. Once generated, the key must be inserted as a query parameter (apikey) in the URL of your
call. For your example:
curl -X GET --header "Accept: application/json" "https://api-lab-trone-stif.opendata.stif.info/service/tr-vianavigo/departures?line_id=100100020%3A20&stop_point_id=59%3A4726914&apikey=<YOUR-API-KEY>"
FYI, the scope of the real-time data available on the dataset tr-unitaire-stif is avalaible here.

Translate this request from Bash to Python?

I was given a request in Bash and I have to translate it to Python 2.7. I did this kind of translations several times, but now I am not able to make it work and I do not understand why.
First of all, I was given this Bash request:
curl -X POST -v -u user#domain:password --data "#file.json" -H "Content-Type:application/json" http://destination_url_a
With the file file.json, whose content is the following one:
{
"username":"user#domain",
"password":"password",
"shortName":"a-short-name",
"visibility":"PRIVATE",
"sitePreset":"site-dashboard",
"title":"A Title",
"description":"A description."
}
If I execute the Bash line in my computer, the result is succesful.
As always, I tried to use requests library in Python to make it work. What I did is:
import requests
from requests.auth import HTTPBasicAuth
import json
data = {
"username": "user#domain",
"password": "password",
"shortName": "a-short-name",
"visibility": "PRIVATE",
"sitePreset": "site-dashboard",
"title": "A Title",
"description": "A description.",
}
headers = {'Content-Type': 'application/json'}
data_json = json.dumps(data)
r = requests.post(
url='http://destination_url_a',
data=data_json,
headers=headers,
auth=HTTPBasicAuth('user#domain', 'password'),
verify=False,
)
Unfortunately, the response, stored in r variable, is an error, despite the status code is 200.
What could be happening? Does anyone find a problem in my code or has any idea?
EDIT
However, this is another example very similar which worked perfectly:
Bash:
curl -v -H "Content-Type:application/json" -X POST --data "#file.json" -u user#domain:password http://destination_url_b
My Python code
import requests
from requests.auth import HTTPBasicAuth
import json
data = {
"userName": "user#domain",
"password": "password",
"firstName": "Firstname",
"lastName": "Lastname",
"email": "email#domain.com",
"disableAccount": "False",
"quota": -1,
"groups": ["a_group",],
}
headers = {'Content-Type': 'application/json'}
data_json = json.dumps(data)
r = requests.post(
url='http://destination_url_b',
data=data_json,
headers=headers,
auth=HTTPBasicAuth('user#domain', 'password'),
verify=False,
)
It seems to be almost the same to the other request, but this works. Different data is sent, and to a different subdomain (both are sent to the same domain). Will these modifications be important if we are talking about the User-Agent you mentioned?
Sometimes, webservices filter on user-agent. User agent of curl and python are different. That may explain.
Try to forge a "legitimate" user-agent by modifying the request header.
Finally, there was no error in the code neither in the User-Agent.
The problem was that the destination application did not accept sites with the same short-name value.
What I was doing is creating the site from Bash, which worked, then removing it from the interface of the app and trying to create it from Python with the same data. I was getting error when doing that because in spite of having removed the site, I had to remove some residual data of it from the trashcan of the app too. If not, app returned an error since it considered that the site I was trying to create already existed.
So if I had introduced different short-name in each attempt, I would not have had any error.

Categories