Posting data on Airtable API does not work - python-3.x

I am trying to create a new table on Airtable with the aid of the post method. I have the following code :
# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "https://api.airtable.com/v0/appa3r2UUo4JxpjSv/Table%201?api_key=MYKEY"
# data to be sent to api
data = {
'fields': {
'Name': 'Andromachis Row'
}
}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
print(r.text)
Despite that when I run the script I get an error saying:
(mypyth) PS C:\Users\andri\PythonProjects\mypyth> py post_API.py
{"error":{"type":"INVALID_REQUEST_UNKNOWN","message":"Invalid request: parameter validation failed. Check your request data."}}
Does anyone understand why this happens? I am really desperate! Thanks in advance

Related

Urllib3 POST request with attachment in python

I wish to make a post request to add an attachment utilising urllib3 in python without success. I have confirmed the API itself is working in postman but cannot work out how to convert this request to python. Appreciating I'm mixing object types I just don't know how to avoid it.
Python code:
import urllib3
import json
api_key = "secret_key"
header = {"X-API-KEY": api_key, "ACCEPT": "application/json", "content-type": "multipart/form-data"}
url = "https://secret_url.com/api/"
http = urllib3.PoolManager()
with open("invoice.html", 'rb') as f:
file_data = f.read()
payload = {
"attchment": {
"file": file_data
}
}
payload = json.dumps(payload)
r = http.request('post', url, headers = header, fields = payload)
print(r.status)
print(r.data)
Postman - which works and properly sends file-name through also (I'm guessing it splits the bytes and filename up?)
Edit: I've also tried the requests library as I'm more familiar with this (but can't use it as the script will be running in AWS lambda). Removing the attachment element form the dict allows it to run but the API endpoint gives 401 presumably because it's missing the "attachement" part to the data structure as per postman below... but when I put this in I get runtime errors.
r = requests.post(url, headers = header, files={"file": open("invoice.html", 'rb')})
For anyone who stumbles upon this from Dr google a few points:
I was completely mis-interpreting the structure of the element. It's actually a string "attachment[file]" not a dict like object.
Postman has the ability to output python code in urllib/request syntax albeit not 100% what I was after. Note: the chrome version (depreciated) outputs gibberish code that only half works so the client version should be used. A short bit of work below shows it working as expected:
http = urllib3.PoolManager()
with open("invoice.html", "rb") as f:
file = f.read()
payload={
'attachment[file]':('invoice.html',file,'text/html')
}
r = http.request('post', url, headers = header, fields = payload)

Python3 Request from API return Not Found

I am trying to get a balance from some address at a explorer on Python but I get 404 error and I believe that is related to a list.
This is my code:
import urllib.request, json, requests
listAddress = [
"HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf"
]
explorerUrl = 'http://explorer.htmlcoin.com'
urlBase = '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/'
balance = '/balance'
for address in listAddress:
urlGamb = explorerUrl+urlBase+address+balance
json_data = urlGamb
r = requests.post(json_data)
r.status_code
r.json()
print(r.json())
The problem is that returns this error:
python3 newwork.py
{'status': 404, 'url': '/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance', 'error': 'Not found'}
So, what am I doing wrong here?
Minor suggestion:
urlGamb = f"{explorerUrl}{urlBase}{address}{balance}"
I don't know about the API, you did not provide a link, but the value of urlGamb is 'http://explorer.htmlcoin.com/api/tokens/Hj5mkJmDWKq8HAh9qDYLnbohZHw6kaUG3A/addresses/HiaRFZkLiWaUuu2x3Dxg2rAMu6BTrzoitf/balance' and that is not JSON. The assignment to json_data seems like a conceptual error because the URL string is not json. If the post requires a JSON payload then the docs should tell you how to construct it.
Should the post have been a get request instead? That would make sense because according to REST standards, post is for changing state on the server, and you are only making a query.

Status code 400 with my GET request - Mixpanel API

I am new to python so please be kind! I'm trying to get event data from Mixpanel's export API. I've been able to do this successfully in Talend and Postman but I want to be able to program it in Python.
Try as I might, I'm having no luck. I keep getting a status code of 400.
import requests
import base64
enc = base64.b64encode(b'my-api-secret').decode("ascii")
headers = {f'Authorization': 'Basic {enc}'}
data = {
'from_date': '2019-02-01',
'to_date': '2019-02-03'
}
response = requests.get('https://data.mixpanel.com/api/2.0/export/', data=data, auth=headers)
Any help would be greatly appreciated.
Thanks!

Facebook messenger chatbot with Flask and pymessenger

I have created a messenger chatbot with flask, pymessenger and wit.ai.
I want to add facebook provided templates (like buttons, adding images and sound media)(https://developers.facebook.com/docs/messenger-platform/reference/template/button/)
There using some curl and json thing which I do not understand. Can some one help me, where should I put these snippet in my python code.
#app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
log(data)
if data['object'] == 'page':
for entry in data['entry']:
for messaging_event in entry['messaging']:
sender_id = messaging_event['sender']['id']
recipient_id = messaging_event['recipient']['id']
if messaging_event.get('message'):
if 'text' in messaging_event['message']:
messaging_text = messaging_event['message']['text']
else:
messaging_text = 'no text'
response = None
entity, value = wit_response(messaging_text)
if entity == 'newstype':
response = "OK. I will send you {} news".format(str(value))
elif entity == 'cust_greet':
response = get_message()
elif entity == 'cust_bye':
response = "Bye! Have a Good Day!".format(str(value))
elif entity == 'cust_option':
response = "Option 1: Option 2:"
bot.send_text_message(sender_id, response)
return "ok", 200
def log(message):
print(message)
sys.stdout.flush()
HTTP requests use one of these two formats:
GET: All the request information is in the url
POST: Some information is sent via a JSON format to the url
What we see in the Facebook API is a POST request: the url is defined as
https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>
...and there is POST request information in the JSON section underneath
Curl is a program used to send HTTP requests from the terminal. If you install Curl, you can fill in the JSON/url information, run the command (which sends the POST request), and see the buttons pop up for the recipient. Just as you want your chatbot to do!
However, Curl is a tool, not a Python library!
To do this in Python, you can send the request through Python's built in libraries, or install a package which makes this easier (such as requests), look into "sending http requests via python".
Below is an example (adapted from this question):
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# the url we are sending the request to
url = "https://graph.facebook.com/v2.6/me/..."
# the POST request data
request_data = {
"recipient": {
"id": "<PSID>"
},
"message": {
"attachment": {
...
}
}
}
# create the request with the url and the data
post_request = Request(url, urlencode(request_data).encode())
# send it to Facebook! Response is the API response from Facebook
response = urlopen(post_request).read().decode()

requests.Session POST not allowing login

I am attempting to scrape some data from an internal GUI for a modem in the field. Here is the code I am using:
## import the requests python library
import requests
## defines the login URL and the Post URL
post_loginURL = 'http://100.255.255.255/cgi-bin/login.cgi'
## defines the request URL to scrape from
requestURL = 'http://100.255.255.255/cgi-bin/stat_eth0.cgi'
## define the login data paramaters
payload = {
'NAME': 'username',
'PWD': 'password',
'CMD': '1' ## hidden value being passed in the post request
}
## define the content type as text/html
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
## creates the session object
with requests.Session() as session:
## sends the post request, headers and login data to the server
post = session.post(post_loginURL, data=payload, headers=headers)
r = session.get(requestURL)
print(r.text)
Here is the HTML Error message I receive in the IDLE console:
<em><u><p align="right">ERROR: You must log in</u></em>
Here are the details from the Chrome Dev Tools:
screenshot
I am unsure if I am just missing a crucial step, or if this is an issue with syntax, etc. Any constructive advice is greatly appreciated.
Thanks in advance!

Resources