I found this script online:
import httplib, urllib
params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("bugs.python.org")
conn.request("POST", "", params, headers)
response = conn.getresponse()
print response.status, response.reason
302 Found
data = response.read()
data
'Redirecting to http://bugs.python.org/issue12524'
conn.close()
But I don't understand how to use it with PHP or what everything inside the params variable is or how to use it. Can I please have a little help with trying to get this to work?
If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:
>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': '12524', 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker
</title>
<link rel="shortcut i...
>>>
This is a solution without any external pip dependencies, but works only in Python 3+ (Python 2 won't work):
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'} # Set POST fields here
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
Sample output:
{
"args": {},
"data": "",
"files": {},
"form": {
"foo": "bar"
},
"headers": {
"Accept-Encoding": "identity",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.3"
},
"json": null,
"origin": "127.0.0.1",
"url": "https://httpbin.org/post"
}
You can't achieve POST requests using urllib (only for GET), instead try using requests module, e.g.:
Example 1.0:
import requests
base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)
payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)
print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP
Example 1.2:
>>> import requests
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
Example 1.3:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
Use requests library to GET, POST, PUT or DELETE by hitting a REST API endpoint. Pass the rest api endpoint url in url, payload(dict) in data and header/metadata in headers
import requests, json
url = "bugs.python.org"
payload = {"number": 12524,
"type": "issue",
"action": "show"}
header = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
response_decoded_json = requests.post(url, data=payload, headers=header)
response_json = response_decoded_json.json()
print(response_json)
Your data dictionary conteines names of form input fields, you just keep on right their values to find results.
form view
Header configures browser to retrieve type of data you declare.
With requests library it's easy to send POST:
import requests
url = "https://bugs.python.org"
data = {'#number': 12524, '#type': 'issue', '#action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)
print(response.text)
More about Request object: https://requests.readthedocs.io/en/master/api/
If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2
urllib2.urlopen(url, body)
See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.
You can use the request library to make a post request.
If you have a JSON string in the payload you can use json.dumps(payload) which is the expected form of payload.
import requests, json
url = "http://bugs.python.org/test"
payload={
"data1":1234,'data2':'test'
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text , response.status_code)
Related
Unable to figure out how to connect branch.io api to jupyter notebook and see what data is there?
Since I'm very new to branch.io, not able to understand the documentation as well.
Can someone help me how to connect the same if anyone has done previousl?
Please try the following
import requests
url = "https://api2.branch.io/v3/export"
payload = {
"branch_key": "xxxxx",
"branch_secret": "xxxx",
"export_date": "2023-02-20"
}
headers = {
"accept": "application/json",
"content-type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
more information here.
https://help.branch.io/developers-hub/reference/requestdailyexport
I understand that HubSpot api provides an endpoint to search contact by name or email?
Is there a way to search a contact by phone number with the API?
For an online tool with a free trial, you can try Acho. Our company uses it to fetch data from HubSpot and use its built-in search bar to search for a specific contact that we need.
Below Python code works on my side.
This page looks very useful.
Cheers!
import hubspot
from pprint import pprint
from hubspot.crm.deals import PublicObjectSearchRequest, ApiException
api_key = "your api key"
test_search_url = f'https://api.hubapi.com/crm/v3/objects/contact/search?hapikey='+api_key
headers = {"Content-Type": "application/json"}
payload = {
"filterGroups": [
{
"filters": [
{
"propertyName": "phone",
"operator": "EQ",
"value": "1234567"
}
]
}
],
"properties": [
"firstname", "lastname", "email", "hs_object_id"
]
}
res = requests.post(test_search_url, headers=headers, data=json.dumps(payload))
res.json()
####Output####
# {'total': 1,
# 'results': [{'id': '13701',
# 'properties': {'createdate': '2022-02-10T07:27:18.733Z',
# 'email': 'adi#XXX.com',
# 'firstname': 'XXX K.',
# 'hs_object_id': '13701',
# 'lastmodifieddate': '2022-02-10T07:28:01.033Z',
# 'lastname': None},
# 'createdAt': '2022-02-10T07:27:18.733Z',
# 'updatedAt': '2022-02-10T07:28:01.033Z',
# 'archived': False}]
# }
I have a function for exactly that written in Python.
The function returns an array of contact's IDs, but you can retrieve other properties if you want, you have to add them in properties=["id"]
from hubspot import HubSpot
from hubspot.crm.contacts import ApiException
from hubspot.crm.contacts import PublicObjectSearchRequest
def get_contacts_by_phone(phone):
api_client = HubSpot()
api_client = HubSpot(access_token=YOUR_TOKEN)
public_object_search_request = PublicObjectSearchRequest(
filter_groups=[],
sorts=[{"propertyName": "phone", "direction": "DESCENDING"}],
properties=["id"],
query=phone,
limit=100,
)
try:
api_response = api_client.crm.contacts.search_api.do_search(
public_object_search_request=public_object_search_request
)
print(api_response)
contacts_ids = []
for contact in api_response.results:
contacts_ids.append(contact.id)
return contacts_ids
except ApiException as e:
print("Exception when calling search_api->do_search: %s\n" % e)
I've the following route:
#http.route([
'/whatever/create'
], auth="none", type='json', methods=['POST'], csrf=False)
which I'm using to send a post request with json data on its body.
Is there any way to avoid using json-rpc responses on routes of type="json"? I would like to just answer plain json.
If it is not possible, is there any way to get the json data placed on the body request by using `type="http"?
#http.route('/whatever/create', auth='public', methods=['POST'], type='http')
def index(self, **kw):
data = request.httprequest.data
return 'success'
Above code defined in Odoo
url = "http://localhost:8069/whatever/create"
param = {
"type_operation": "PTI",
"label": "",
}
headers = {'Content-type': 'text/plain'}
r = requests.post(url, data=json.dumps(param), headers=headers)
Above code i have requested from a py file
While sending request you should change Content-type
'Content-type': 'application/json' --- > 'Content-type': 'text/plain'
Also while returning it only accept String
return {'status': 'success'} ---> return 'success'
I am trying to POST a request to Kibana using the "/api/console/proxy" path.
I have 3 headers in my request:
es_headers = {
'kbn-version': "5.5.0",
'Content-Type': "application/json",
'Cookie': "session_2=eyJhbGciOi....(long string)"
}
I am using Python requests as following:
session = requests.Session()
r = session.post(url, timeout=15, data=json.dumps(body), headers=es_headers)
From "Postman" it works just fine, but from my Python script I get a [200] response but the content of the response is like this:
'Error encountered = Unable to decrypt session details from cookie. So
clearing it.'
I googled this response but couldn't find any info about it (which is weird ...)
Any help appreciated here
Thanks
Try including the cookies separately from the headers, like this:
import requests
es_headers = {
'kbn-version': "5.5.0",
'Content-Type': "application/json",
}
session = requests.Session()
session.cookies.update({'Cookie': "session_2=eyJhbGciOi....(long string)"})
r = session.post(url, timeout=15, data=json.dumps(body), headers=es_headers)
hope this helps
I tried to subscribe to onedrive webhooks by hitting
https://graph.microsoft.com/v1.0/subscriptions
https://graph.microsoft.com/beta/subscriptions
parameters are:
"changeType": "created,updated,deleted",
"notificationUrl": url.
"resource": "me/drive/root",
"clientState": "client-specific string",
"expirationDateTime": "2018-01-01T11:23:00.000Z",
I am getting an error like below:
{ error:
{ code: 'InvalidRequest',
message: 'Server could not process subscription creation payload.',
innerError:
{ 'request-id': 'id',
date: '2018-10-16T09:16:46' } } }
I am trying it in my local.
Is there any solution ?
Make sure you post a json request, that means:
Request body is a json string;
'Content-Type' field in headers, and value is 'application/json'
If you use Python, there is a shortcut:
import requests
url = "https://graph.microsoft.com/beta/subscriptions"
headers = {'Authorization': 'Bearer ' + "YOUR_TOKEN"}
data = {
"changeType": "created,updated,deleted",
"notificationUrl": url.
"resource": "me/drive/root",
"clientState": "client-specific string",
"expirationDateTime": "2018-01-01T11:23:00.000Z"
}
resp = requests.post(headers=headers, json=data)
I had the same problem trying the request with Postman. The body was in x-www-form-urlencoded format. It worked when I changed the body format to raw and specified JSON.
Not working "x-www-form-urlencoded" format
Working "raw" format
It looks like MS Graph API only accepts certain input formats. Hope this will help!