I'm trying to generate an http(s) request via Python Requests however I'm running into a problem:
No connection adapters were found for 'set(['http://www.example.com/target'])'
I'm attempting to make the connection like so:
url = ['http://www.example.com/target']
headers = {"Content-Type":"application/json"}
ver = False;
message = { bunch of json data }
curl_request(url,message,headers,ver)
With the curl_request API call being:
# API call to perform curl request and return resulting json status
def curl_request(url,message,headers,ver):
requests.post(url, data=json.dumps(message), verify=ver, headers=headers)
data = response.json()
return data
Use a string, not a set.
url = 'http://www.example.com/target'
Related
bascially i am making a route in which i have connect my api of whatapp when i send a number in my json response thought software this route should send me a whatapp message on that number
#app.route('/v1.1/userRegistor', methods=['POST','GET'])
def get_user():
data = request.get_json()
numbers=data['numbers']
api_url = ('https://app.simplywhatsapp.com/api/send.php?number=numbers&type=text&message=test%20message&instance_id=634CF8BECCB26&access_token=78495efca3672167f9ed88cb93acd2e1')
r = requests.get(api_url)
return r.json()
this is my request body:
{
"numbers":"923142985338"
}
You aren't formatting your API request URL. The variables can't be passed directly in the string, as they can't be distinguished from words. You need to use a format string.
api_url = f'https://app.simplywhatsapp.com/api/send.php?number={numbers}&type={text}&message=test%20message&instance_id=634CF8BECCB26&access_token=78495efca3672167f9ed88cb93acd2e1'
Read more about it here: https://www.pythoncheatsheet.org/cheatsheet/string-formatting
I am trying to simulate a web request using python library. This is the get request query created by the browser(I have replaced the actual url)
http://myurl.asp?treg=8338033&dob=14/09/2003&sid=0.3582164869592499
My code is here.
def individual(reg,dob):
session = Session()
myurl='http://myurl.asp'
# HEAD requests ask for *just* the headers, which is all you need to grab the
# session cookie
session.head('http://myurl')
response = session.get(
url=myurl,
data={
'treg': reg,
'dob': dob,
'sid':'0.4443253265244038'
},
headers={
'Referer': 'http://myurl.htm'
}
)
return response.text
It gives me invalid date response from server. But the same values sent through browser is successful. I have already tried yyyy-mm-dd format.
You are mixing up GET-style params with POST ones by using data instead of params in the request session.get call.
Python Request Post with param data
and thank you for you useful help already.
I am trying to make an API call using python. Sadly, the only documentation of the API is an implementation already existing in C#.
My problem is, that after i acquire an Azure AADTokenCredential object - i simply do not know how to use it in my HTTPS request.
def get_data_from_api(credentials):
serialNumber = "123456789"
fromDate = "01/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS
untilDate = "09/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS
PARAMS = {
serialNumber: serialNumber,
fromDate: fromDate,
untilDate: untilDate
}
url = "https://myapi.azurewebsites.net/api/sensordata/GetBySerialNumber"
r = requests.get(url = url, header={"Authorization": credentials}, params=PARAMS)
print(r)
#data = r.json()
return data
The credentials is an msrestazure.azure_active_directory.AADTokenCredentials retrieved using the adal package.
The above code results in an error as the header object can only be strings.
My question is - How do i pass the authorization object in the correct way?
The C# implementation looks like this:
// Make a request to get the token from AAD
AuthenticationResult result = Task.Run(async () => await authContext.AcquireTokenAsync(resource, cc)).Result;
// Get the auth header which includes the token from the result
string authHeader = result.CreateAuthorizationHeader();
// ...
// Prepare a HTTP request for getting data.
// First create a client
HttpClient client = new HttpClient();
// Create the actual request. It is a GET request so pass the arguments in the url is enough
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, $"https://api.azurewebsites.net/api/sensordata/GetBySerialNumber?serialNumber={serialNumber}&from={fromDate}&until={untilDate}");
// Add the required authorization header that includes the token. Without it the request will fail as unauthorized
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
// Prepare the response object
HttpResponseMessage response = Task.Run(async () => await client.SendAsync(request)).Result;
So yes! I finally solved it.
My problem was that i was passing on the ADAL object to the requests phase, however what I needed to do was pass on the actual token that is retrieved using: 'credentials = context.acquire_token_with_client_credentials(resource_uri,client_id,client_secret)'.
Here credentials is a dictionary and what the requests needs in the header for authentication was:
header = {
"Authorization": "Bearer "+credentials["accessToken"]
}
r = requests.get(url=url, headers=header, params=PARAMS)
passing this on to the requests.get method worked!
I'm trying to retrieve the response json data by a web site that I call.
The site is this:
WebSite DriveNow
On this page are shown on map some data. With browser debugger I can see the end point
end point
that sends response data json.
I have use this python to try scrape the json response data:
import requests
import json
headers = {
'Host': 'api2.drive-now.com',
'X-Api-Key': 'adf51226795afbc4e7575ccc124face7'
}
r = requests.get('https://api2.drive-now.com/cities/42756?expand=full', headers=headers)
json_obj = json.loads(r.content)
but I get this error:
hostname doesn't match either of 'activityharvester.com'
How I can retrieve this data?
Thanks
I have tried to call the endpoint that show json response using Postam, and passing into Header only Host and Api-Key. The result is the json that i want. But i i try the same call into python i recive the error hostname doesn't match either of 'activityharvester.com'
I don't understand your script, nor your question. Why two requests and three headers ? Did you mean something like this ?
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0',
'X-Api-Key':'adf51226795afbc4e7575ccc124face7',
}
res = requests.get('https://api2.drive-now.com/cities/4604?expand=full', headers=headers, allow_redirects=False)
print(res.status_code, res.reason)
json_obj = json.loads(res.content)
print(json_obj)
I am trying to send a POST request with a Neo4j transaction query. Although I get a response 200 the node is not created. This is my Python script:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"query" : '{"statements": [{"statement":"CREATE (n:test) RETURN n"}]}'}
mkr =requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr)
I haven't used transactions before and nver tried to create one through the Rest Api. What am I doing wrong here?
It seems unlikely to me that you're receiving a response code of 200; you should be getting a 500 as the transactional endpoint doesn't accept a query parameter. Try this:
import requests
import json
import csv
headers = {'content-type': 'application/json'}
url = "http://localhost:7474/db/data/transaction/commit"
checkNode = {"statements":[{"statement":"CREATE n RETURN n"}]}
mkr = requests.post(url, data=json.dumps(checkNode), headers=headers)
print(mkr.text)