So I am using the urban dictionary api, and the code works perfectly as I would like: I'm going to use chicken as my term.
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
print(json.dumps(json_object, indent = 4))
If I run this, I get the following which is the correct output, but I want to only print out the definition.
{
"list": [
{
"definition": "A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"",
"permalink": "http://chicken.urbanup.com/1180537",
"thumbs_up": 2947,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "DEKE",
"word": "chicken",
"defid": 1180537,
"current_vote": "",
"written_on": "2005-04-11T11:41:04.000Z",
"example": "Person 1) [How much] you [got left]?\r\n\r\nPerson 2) A [quarter] chicken.",
"thumbs_down": 941
},
{
"definition": "To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]",
"permalink": "http://chicken.urbanup.com/7399878",
"thumbs_up": 180,
"sound_urls": [
"http://api.twilio.com/2008-08-01/Accounts/ACd09691b82112e4b26fce156d7c01d0ed/Recordings/RE18c37ff43a6fc6dce8d9d533e7e4042b"
],
"author": "Freak Out Guy",
"word": "chicken",
"defid": 7399878,
"current_vote": "",
"written_on": "2013-12-10T16:49:06.660Z",
"example": "He was so afraid she [thought] he was [a chicken].",
"thumbs_down": 49
}
]
}
I've seen that you can do print(json_object['list'][0]['definition']), but it only prints out the first definition. How can I print out all the instances of definition like:
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos \"[birds]\" which then evolved into \"chicken.\"
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
for idx, entry in enumerate(json_object['list'], 1):
print(f'Definition {idx}: {entry["definition"]}')
output
Definition 1: A [kilogram] of [cocain]. Dealers started calling kilos "[birds]" which then evolved into "chicken."
Definition 2: To lack courage and [bravery]. [Unskilled], stupid, afraid, loser, [coward]
You dont need to use the dump, u can use the json_object instead. Like this:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
print(json_object["list"][0]["definition"]) # you can use the for statement to get all the definitions
(Edit) All the definitions example:
import json
import requests
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"chicken"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "KEY"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data = response.text
json_object = json.loads(json_data)
#json_object = json.dumps(json_object, indent = 4)
for i in json_object["list"]:
print(i["definition"])
Related
I want to use the Microsoft Graph API to send messages with attachments to chats or channels.
https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=http#example-4-send-a-message-with-file-attachment-in-it
I can send normal messages already just fine like this:
def post_message(chat_id: str, subject: str = "", content_type: str = "text", content: str = "") -> None:
url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
json = {
"subject": subject,
"body": {
"contentType": content_type,
"content": content
}
}
res = requests.post(url, headers=header, json=json)
I try to copy the body from the example in the link above, substitute for my values and swap json variable for this one:
attachment_id = '7QW90B10D7-B5AK-420A-AC78-1156324A54F2' # not real, only to show how it looks like
json = {
"body": {
"contentType": 'html',
"content": f'i dunno what i\'m doing. <attachment id="{attachment_id}"></attachment>'
},
'attachments': [
{
'id': attachment_id,
'contentType': 'reference',
'contentUrl': 'https://foo.sharepoint.com/sites/bar/User%20documentation/Databricks/Databricks%20guide.pptx',
'name': 'Databricks guide.pptx'
}
]
}
I get requests.exceptions.HTTPError: 400 Client Error: Bad Request for url
What's wrong with the code? How to get attachment id from a file correctly because I am not sure I got the right value?
I was able to get it working with your code, (using both formats <attachment id=\"\"> and <attachment id="">), so it seems the error is probably with your attachment_id.
I retrieved the driveItem ID by following this answer, where the driveItem ID is the GUID value in the eTag property in the response.
You could get the file by the path:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/{item-path}
For example:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/test.docx
If the file is in a folder, it would be like this:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/folder1/test.docx
Sample request after obtaining the ID
access_token = ""
attachment_name = "file.txt"
attachment_path = "https://domain.sharepoint.com/Shared%20Documents"
attachment_id = "12345678-1234-1234-1234-123456789123"
attachment_url = f"{attachment_path}/{attachment_name}"
chat_id = ""
req_url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
req_headers = {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
}
json = {
"body": {
"contentType": "html",
"content": f"Test message <attachment id=\"{attachment_id}\"></attachment>"
},
"attachments": [
{
"id": attachment_id,
"contentType": "reference",
"contentUrl": attachment_url,
"name": attachment_name
}
]
}
result = requests.post(url = req_url, headers = req_headers, json = json)
I am trying to extract data from an API with python.
With this code, I am trying to print the content of dictionaries within a list.
response = requests.get(url, params=payload)
data = response.json()
log = json.dumps(data['result'], indent = 1)
print log
So far so good, it prints:
[
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
{
"line": "something#gmail.com:birthdaydate"
},
]
Is there a way for the output to look like below?
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
"something#gmail.com:birthdaydate"
Try this one:
response = requests.get(url, params=payload)
data = response.json()
log = data['result']
for l in log:
print(l["line"])
I want to make a list from api json response as shown for each ticket in jira and remove any duplicates
I can get the values for each ticket but not able to make it as list and remove duplicates from it to process
Here is the api json response for each ticket
response = {
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "1831845",
"self": "https://jira.com/login/rest/api/latest/issue/1845",
"key": "pc-1002",
"fields": {
"customfield_1925": {
"self": "https://jira.com/login/rest/api/2/customFieldOption/1056",
"value": "windows",
"id": "101056"
}
so i have script like this:
import requests, json
tick = """jira: pc-1002,pc-1003,pc-1005
env"""
ticks = tick.replace(' ','').split(':')[1].split('\n')[0].split(',')
print(ticks)
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
print(resp)
so it prints all the values like below :
output:
windows1
windows2
windows1
I want the output values to be unique and as it may end up having duplicates.
I wanted output as below
['windows1', 'windows2']
Simply add each response to a list of responses, and use Python's convenient "in" operator to check if each response is already in the list. Something along the lines of:
allResponses = []
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
if resp not in allResponses:
print(resp)
allResponses.append(resp)
I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type
I am baffled and do not know how to solve this error. I'm trying to grab every name inside a JSON response list.
My code looks like this.
def extract_strucutres_ids(expected_structures):
response = requests.get(JIRA_REST + "/structures", verify=False)
response = response.json()
for structure in response['structures']:
print structure['name']
The Json reponse looks like this.
{
"structures": [{
"id": 165,
"name": "6.2 External Notifications Refactor",
"description": ""
}, {
"id": 364,
"name": "6.4 Day/Night Mode and Idle Scene Mode",
"description": "",
"readOnly": true
}, {
"id": 140,
"name": "ACC 5 Regression",
"description": ""
}
]
}
I keep getting List indicies must be integers, not str.
Python version 2.7.10
try this -
import json
def extract_strucutres_ids(expected_structures):
response = requests.get(JIRA_REST + "/structures", verify=False)
if response.status_code==200:
response_json = json.loads(response.text)
for structure in response_json['structures']:
print structure['name']
else:
print("Response is {}".format(response.status_code))
Let me know,if it worked!
Use json.loads()
response = requests.get(..)
response = json.loads(response.text) # response.text is a string
for structure in response['structures']:
# Do something