The documentation of the API is here, and I try to implement this line in python
//retrieve entries created on a specific day (use the date_created field)
//this example returns entries created on September 10, 2019
https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/10/2019","operator":"is"}]}
But when I try to do with python in the following code, I got an error:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
url = 'https://localhost/wp-json/gf/v2/entries?search={"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}'
r = session.get(url)
print(r.content)
The error message is :
ValueError: Error trying to decode a non urlencoded string. Found invalid characters: {']', '['} in the string: 'search=%7B%22field_filters%22:%20[%7B%22key%22:%22date_created%22,%22value%22:%2209/01/2023%22,%22operator%22:%22is%22%7D]%7D'. Please ensure the request/response body is x-www-form-urlencoded.
One solution is to parameterize the url:
import requests
import json
url = 'https://localhost/wp-json/gf/v2/entries'
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
headers = {'Content-type': 'application/json'}
response = session.get(url, params=params, headers=headers)
print(response.json())
But in the retrieved entries, the data is not filtered with the specified date.
In the official documentation, they gave a date in this format "09/01/2023", but in my dataset, the format is: "2023-01-10 19:16:59"
Do I have to transform the format ? I tried a different format for the date
date_created = "09/01/2023"
date_created = datetime.strptime(date_created, "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S")
What alternative solutions can I test ?
What if you use urllib.parse.urlencode function, so your code would looks like:
import json
import oauthlib
from requests_oauthlib import OAuth1Session
import urllib.parse
consumer_key = ""
client_secret = ""
session = OAuth1Session(consumer_key,
client_secret=client_secret,signature_type=oauthlib.oauth1.SIGNATURE_TYPE_QUERY)
params = {
"search": {"field_filters": [{"key":"date_created","value":"09/01/2023","operator":"is"}]}
}
encoded_params = urllib.parse.urlencode(params)
url = f'https://localhost/wp-json/gf/v2/entries?{encoded_params}'
r = session.get(url)
print(r.content)
hope that helps
I had the same problem and found a solution with this code:
params = {
'search': json.dumps({
'field_filters': [
{ 'key': 'date_created', 'value': '2023-01-01', 'operator': 'is' }
],
'mode': 'all'
})
}
encoded_params = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = 'http://localhost/depot_git/wp-json/gf/v2/forms/1/entries?' + encoded_params + '&paging[page_size]=999999999' # nombre de réponses par page forcé manuellement
I'm not really sure what permitted it to work as I'm an absolute beginner with Python, but I found that you need double quotes in the URL ( " ) instead of simple quotes ( ' ), so the solution by William Castrillon wasn't enough.
As for the date format, Gravity Forms seems to understand DD/MM/YYYY. It doesn't need a time either.
Related
I'm writing code to access the MS365 API and the Python code example uses urllib. I want to instead use requests but I'm not sure how urllib translates into requests as my attempts of doing so have failed.
The code example can be found here:
https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/run-advanced-query-sample-python?view=o365-worldwide#get-token
import json
import urllib.request
import urllib.parse
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
body = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
data = urllib.parse.urlencode(body).encode("utf-8")
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]
IIUC, this should work the same:
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
params = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.get(url, params)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]
Modifying #BeRT2me's answer has made this work.
import requests
tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
data = {
'resource' : resourceAppIdUri,
'client_id' : appId,
'client_secret' : appSecret,
'grant_type' : 'client_credentials'
}
response = requests.post(url=url, data=data)
jsonResponse = response.json()
aadToken = jsonResponse["access_token"]
I am working with the Spotify API. I am trying to generate an access token. I followed along https://www.youtube.com/watch?v=xdq6Gz33khQ this video to generate the token.
I am getting an error
{'error': 'invalid_client'}
The code I have written is:
import base64
from wsgiref import headers
import requests
import json
client_id = "09e0b9beeba74aee986546f496823d60"
client_secret = "be1c93f2a446477e8416235b2a3f442c"
# searching for token which will help in authorization
client_creds = f"{client_id} : {client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_url = "https://accounts.spotify.com/api/token"
method = "POST"
token_data = {
"grant_type": "client_credentials"
}
token_header = {
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
}
r = requests.post(token_url, data=token_data, headers=token_header)
print(r.json())
Not sure why I get this error. It could be the link I am using for the token url but can't find what to replace it with.
change
client_creds = f"{client_id} : {client_secret}"
to
client_creds = f"{client_id}:{client_secret}"
change
"Authorization" : f"Basic {client_creds}" # <base64 encoded client_id:client_secret>
to
"Authorization": f"Basic {client_creds_b64.decode()}"
POSTURL = 'https://partner.spreadshirt.de/login'
REQURL = 'https://partner.spreadshirt.de/dashboard'
payload = {
"username": 'test#gmail.com',
"password": 'somepassword'
}
import requests
with requests.Session() as session:
post = session.post(POSTURL, data=payload)
r = session.get(REQURL)
print("String" in r.text)
I know that this String is in present on the Website so this is not the problem. But my code returns False, so maybe I cant get to the REQURL? How could I determine if I got there?
When reviewing the abilities of the Python API for Trello and considering its functionalities,
I was searching for a function that allows to add a member to a board - w./o. success.
What I have tried to use is the following:
trello = TrelloAPI(myAPIKey, myToken)
boardID = myBoardID
fields = {"fullName": "Robo Member",
"email" : myMail}
trello.boards.get_membersInvited(board_id = boardID,
fields = fields)
This is how the method implementation looks like:
def get_membersInvited(self, board_id, fields=None):
resp = requests.get("https://trello.com/1/boards/%s/membersInvited" %
(board_id), params=dict(key=self._apikey, token=self._token,
fields=fields), data=None)
resp.raise_for_status()
return json.loads(resp.content)
I end up receiving 404 Client Error URL not found.
Do you have any suggestions on what to adjust?
Maybe, I used the wrong field names (email and fullName)?
Here is a solution for .NET
Found a remedy by myself. Source --> Trello API Board Put Member
Here my own solution:
def invite_new_member(self, fullName, email, boardID):
url = self.baseURL + "boards/" + boardID + "/members"
querystring = {"email": email, "key": apikey,
"token": token}
payload = "{\"fullName\":\"" + fullName + "\"}"
headers = {
'type': "normal",
'content-type': "application/json" }
response = requests.request("PUT", url, data=payload, headers=headers,
params=querystring)
I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res