How to post json data directly in Rest API with python - python

I have a response data which is in json format, now I want to post this json format.But I have issues with same.
{'u_correlationid_': '', 'resolved_by': '','active': 'true', 'upon_approval': 'proceed', 'skills': '', 'parent_incident': '', 'business_impact': '', 'sys_domain': {'value': 'global', 'link': ''}, 'made_sla': 'true', 'activity_due': '2019-11-07 10:09:15', 'opened_at': '2019-09-11 16:17:24'}
When I tried directly posting the json data I had error:
"error": "Validation error - JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: java.io.PushbackInputStream#37b90445; line: 1, column: 298] (through reference chain: java.util.LinkedHashMap[\"sys_domain\"])"
I want to fix this error in Python and also post my json data with " instead of ' format of my response
E.g-{"u_correlationid":""} and at last I also want to append one key pair to existing before post.
E.g-
{"u_correlationid":"",
"opened_at": "2019-09-11 16:17:24","data":"big"}

Related

How do I get the number of documents in a SharePoint library with Microsoft graph?

Is it possible to know the number of items in a group library?
I tried with f'groups/{group["id"]}/drive', which returns lots of information about the library, but doesn't include the total number of files.
EDIT (followup to Popkornak's answer)
I have tried using the $count parameter, but it doesn't work. Here is the result of the query with and without $count:
> print(requests.get('https://graph.microsoft.com/v1.0/groups/<group-id>/drive',
headers={'ConsistencyLevel': 'eventual', 'Authorization': '<...>'},
params={'$select': 'id', '$count': 'true'}).json())
{'error': {'code': 'invalidRequest', 'message': '$count is not supported on this API. Only URLs returned by the API can be used to page.', 'innerError': {'date': '2022-01-04T16:46:32', 'request-id': '<...>', 'client-request-id': '<...>'}}}
> print(requests.get('https://graph.microsoft.com/v1.0/groups/<group-id>/drive',
headers={'ConsistencyLevel': 'eventual', 'Authorization': '<...>'},
params={'$select': 'id'}).json())
{'#odata.context': 'https://graph.microsoft.com/v1.0/$metadata#drives(id)/$entity', 'id': '<...>'}
Use $count parameter in your query, reffer to oficial Microsoft documentation:
https://learn.microsoft.com/en-us/graph/query-parameters
Please keep in mind that if it will throws an error about not supported parameter use
Header:
Key: “consistencylevel” Value: “eventual”

Django - Why does Django set `request.data` to QueryDict class when a file is attached, but a dict when no file is attached?

So I have a test where I don't attach a file to the request
>>>request.data
{'description': 'Some Goal text', 'end_date': '2021-12-04', 'goal_category': 'health', 'body': 'Some text #blah\r#weeeee\x0c#foo', 'creator': '6badb4b8-33ba-4bb9-aa9a-2e3afb359960', 'type': <PostType.DECLARE: 'DE'>}
>>>type(request.data)
<class 'dict'>
>>> denotes where I input into the debug console and below it is what is printed out. Then I attach a file and send in the request and I get this.
>>>type(request.data)
<class 'django.http.request.QueryDict'>
>>>request.data
<QueryDict: {'join_goal': ['d2f5aa8d-4cd0-4051-9d1a-35b28af276d5'], 'body': ['Some text and an image'], 'images': [<InMemoryUploadedFile: test.jpg (text/plain)>], 'creator': ['6badb4b8-33ba-4bb9-aa9a-2e3afb359960'], 'type': [<PostType.UPDATE: 'UP'>]}>
Why does Django use a QueryDict when an image comes in?
Requested added code
def set_request_data_for_post(request):
request.data['creator'] = str(request.user.uuid)
body_text = request.data['body']
hash_tags = create_hashtags_uuid_list(body_text)
if len(hash_tags) > 0:
request.data.setlist('hash_tags', hash_tags)
tagged_users_list = extract_usernames(body_text)
tagged_users = list()
for username in tagged_users_list:
try:
tagged_users.append(str(User.objects.get(username=username).uuid))
except User.DoesNotExist:
pass
if len(tagged_users) > 0:
request.data.setlist('tagged_users', tagged_users)
return request
This new request var gets passed to a serializer.
When DRF receives a request it select the appropriate parser from the ones defined on the view or from the defaults
The default parsers include the JSONParser which is used when JSON data is received and returns a dict and the MultiPartParser which is used when multipart data (the content type used when uploading files) is received and returns a QueryDict

How can i insert list of Classifications into Apache Atlas using API

I am trying to insert set of classifications or tags into Apache Atlas using API.
I am facing an error.
Can any one help me any roundabouts of overcoming this error and insert the classifications.
My code:
import requests
import json
from requests.auth import HTTPBasicAuth
#specify url
url = 'http://aaaaa/api/atlas/v2/entity/classification'
print(url)
bulk = { "classification":{ "typeName":"Confidential","attributes":{ "retention_required":"true","max_retention_time_months":"12"}},"entityGuids":[ "be532571-1663-4550-af6d-28cfe39769f6"]}
#Call REST API
response = requests.put(url, data=bulk,auth=HTTPBasicAuth('xxx', 'yyy'))
print(response)
print(response.text)
This GUID is valid.
The error I face is :
<Response [500]>
There was an error processing your request. It has been logged (ID 7e31c72f5e0f5e3b).
In short, I want to achieve the given screen functionality thru python.
Thank you.
Send request to: http://aaaaa/api/atlas/v2/types/typedefs
You should use post if the classification doesn't exist already, if the classification exists, you will get 409 Client Error.
Use PUT to update existing classification.
Your json should look something like this:
{'classificationDefs: [{
'entityTypes': entityTypes,
'subTypes': subTypes,
'superTypes': superTypes,
'attributeDefs': attributeDefs,
'category': category,
'createdBy': createdBy,
'description': description,
'name': name,
'options': options,
'typeVersion': typeVersion,
'updatedBy': updatedBy,
'version': version
}]
}
Types of attributes in json:
list: entityTypes, attributeDefs, superTypes, subTypes
dictionary: options
number: version
rest is of type string or text

unable to serialize json array

I am somewhat new to working with API's and am receiving a graphconnection is not serializable error when trying to json.dumps an api response. The response looks to be a json array however, when i run Type(api_response) nothing is output.
Any help would be appreciated.
I have tried Type(api_response)
api_response = api_instance.graph_user_group_members_list(group_id, content_type, accept,limit=limit, skip=skip, x_org_id=x_org_id)
#pprint(api_response)
data = json.dumps(api_response)
I would like to convert the api_response to python dict format so that I can use the json values....
I am receiving this error
TypeError: Object of type GraphConnection is not JSON serializable
This is the output if I print api_response
[{'_from': None, 'to': {'id': '', 'type': 'user'}}, {'_from': None,
'to': {'id': '', 'type': 'user'}}]
It's likely because of the brackets around the json object. The data within the curly braces is valid json. Try to index the api_response (like jsonObject = api_response[0]) to get the 'first element' of the api response object.
I actually was able to find the solution by using ([ob.dict for ob in api_response]). Still think I am missing some knowledge surrounding how json.dumps works.

Google App Engine: Python: WebOb: How to get POST data in JSON format?

I am building a web app on the Google App Engine platform, which uses webapp2, which uses WebOb. I would like to POST some data in JSON format, including nested arrays and dictionaries. E.g.:
$.post('/addvendor', {'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}, function(data){console.log(data)}, 'application/json')
However, on the server side, the data comes in as a flat "MultiDict" object, not anything like the original nested JSON object that I POSTed. E.g.:
>>> print self.request.params.items()
[(u'vendor[name]', u'test'), (u'vendor[description]', u'a good company'), (u'vendor[tags][]', u'foo'), (u'vendor[tags][]', u'bar')]
This object is very difficult to parse. In my server code, is there a way to get the same data in standard JSON format, or at least a Python equivalent using nested dictionaries and arrays, on the server so that I can manipulate and examine the data easily?
(updated with jayhendren's help) You should use $.ajax and manually set contentType='application/json; charset=utf-8' instead because $.post uses default "application/x-www-form-urlencoded;" content type. Also you need to manually encode data to JSON-string with JSON.stringify:
$.ajax({url:'/addvendor',
type: 'post',
data:JSON.stringify({'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}),
contentType:'application/json; charset=utf-8',
dataType: "json",
success:function(data){console.log(data)}})
...
print json.loads(self.request.body)
use json.dumps(yourdata)
don't forgot to change the header Content-Type to application/json
headers = {
"Content-Type": "application/json"
}
session.post(<url>, data=json.dumps(yourdata))

Categories

Resources