Grab a Specific Field from a JSON response in Python - python

I am sending an API request, and I receive the following response:
{
'response':{
'Container List':[
{
'Driver ID':'038107264',
'Status':True,
'Truck':'4314008'
}
]
}
}
What I want to do is to print only the value in Truck, meaning I want to be able to print the value 4314008.

I'm assuming you are using requests to get this resonse
response = requests.get("whateverurl").json()
print(response["response"]["Container List"][0]["Truck"])

Related

Python requests post reponse 400

I have no idea where is error. My response is 400 cuz of it:
"errors":{"data":["The data field is required."
but i am sending 'data':
data = "{'example': 'example'}"
url = f'http://localhost:5219/myApi'
payload = {'data': str(data).encode('utf-8')}
req = requests.post(url, data=payload)
print(req.content)
response
b'{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-355ed090aff5fa10460587fe222edbbe-3b3927cf18b26b78-00","errors":{"data":["The data field is required."]}}'
how can i repair that?
i tried changing formats and other things but it didn't work pls help me
this is c# code from api:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Text.Json.Nodes;
namespace spyware.Api.Controllers
{
[Route("[controller]")]
[ApiController]
public class api : ControllerBase
{
[HttpPost]
public void GetResponse(string data)
{
Console.WriteLine(JsonConvert.DeserializeObject(data.ToString()));
}
}
}

login into Spotify through python requests module

I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy

Server connection and read/write value

I want to read write value from a PLC through API (RESTful like) provide by constructor.
First step is authentification
Ajax code
$.ajax({
url: "http://192.168.10.11/sdcard/cpt/app/signin.php",
type: 'POST', dataType: 'json',data: {
'user[name]': 'admin',
'user[password]': 'hellocpt'
}
}).done(function(data) {
console.debug("signin done");
});
Next I can read value from JSON
var url='http://192.168.10.11/sdcard/cpt/app/data_api.php?
url=/app/objects/EasyIO/Ramp.out';
$.ajax(
{url: url, type: 'GET', dataType: 'json'}
).done(function(data) {console.debug(data);});
Response
{
"response" : {
"resultCode" : 0, // '0' for success, other numbers for
failure
"data" : [ // sedona object data is orgnized in list
{ // every object's data is a dictionary
"path" : "/EasyIO/Ramp", //sedona object's path
"slots" : [ //slots data is organized as a list
{
"value" : "49.000000", // 'out' slot's value
"slotType" : "property", // this slot is a
property
"name" : "out", // slot's name"type" : "float" // slot value's data type
}
]
}
]
}
}
Commande
var url = 'http://192.168.10.11/sdcard/cpt/app/data_api.php';
$.ajax({url: url,
type: 'POST',
dataType: 'json',
data: {
path: '/app/objects/EasyIO/WriteIn.in',
type: 'int',
value: '100',
slotType: 'property'
}
}).done(function(data) {
console.debug(data);
});
Response
{
"response" : {
"resultCode" : 0, // '0' for success, other numbers for
failure
"value" : "100", // slot value has been changed to '100'
"type" : "int", // slot data type is 'int'
"path" : "/app/objects/EasyIO/WriteIn.in" //slot's path
}
}
This API documentation
This my python3 code test
import os
import requests
import pycurl
import json
import urllib
from urllib.request import urlopen
headers = {
'X-Requested-With': 'XMLHttpRequest',
}
data = [
('user[name]', 'admin'),
('user[password]', 'hellocpt'),
]
response = requests.post('http://192.168.0.230/sdcard/cpt/app/signin.php', headers=headers, data=data)
print("Code Status du POST: ",response.status_code)
print(response.content)
cookies = {
}
params = (
('url', '/app/objects/EasyIO/Ramp.out'),
)
responseget = requests.get('http://192.168.0.230/sdcard/cpt/app/data_api.php', headers=headers, params=params, cookies=cookies)
print("\n\nCode Status du GET: ",responseget.status_code)
print(responseget.content)
and my output
Code Status du POST: 200
b'{"redirectUrl": "http://192.168.0.230/sdcard/cpt/dashboard/index.php" }'
Code Status du GET: 200
b'{"redirect": "http://192.168.0.230/sdcard/cpt/app/signin.php"}'
My problem is I don't understand why my POST command working but when I make a GET command I see redirection to signin page link. Why there is a logout?
Anyone can help?
Thanks
When you are sending your second request (GET), how will the server know that you have signed in before? The server sends you back something in the first request which you should send back to the server in your second request so the server can authenticate you.
I wasn't able to find out how your API is working using the ajax codes you have posted because the returned data is not shown in the first request but if we assume that the authentication is cookie based then instead of an empty cookie you should replace this line :
cookies = {
}
with this :
cookies = response.cookies
But this is only an example, your API might return a token instead of using cookies or some other type of authentication which is specified in the documentation.
EDIT : I was able to open the pdf file which contains the API documentation and it seems that the authentication is cookie based so the solution should work.

How to make a post request with the Python requests library?

I am using the following filters in Postman to make a POST request in a Web API but I am unable to make a simple POST request in Python with the requests library.
First, I am sending a POST request to this URL (http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets) with the following filters in Postman applied to the Body, with the raw and JSON(application/json) options selected.
Filters in Postman
{
"filter": {
"filters": [
{
"field": "RCA_Assigned_Date",
"operator": "gte",
"value": "2017-05-31 00:00:00"
},
{
"field": "RCA_Assigned_Date",
"operator": "lte",
"value": "2017-06-04 00:00:00"
},
{
"field": "T_Subcategory",
"operator": "neq",
"value": "Temporary Degradation"
},
{
"field": "Issue_Status",
"operator": "neq",
"value": "Queued"
}],
"logic": "and"
}
}
The database where the data is stored is Cassandra and according to the following links Cassandra not equal operator, Cassandra OR operator,
Cassandra Between order by operators, Cassandra does not support the NOT EQUAL TO, OR, BETWEEN operators, so there is no way I can filter the URL with these operators except with AND.
Second, I am using the following code to apply a simple filter with the requests library.
import requests
payload = {'field':'T_Subcategory','operator':'neq','value':'Temporary Degradation'}
url = requests.post("http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets",data=payload)
But what I've got is the complete data of tickets instead of only those that are not temporary degradation.
Third, the system is actually working but we are experiencing a delay of 2-3 mins to see the data. The logic goes as follows: We have 8 users and we want to see all the tickets per user that are not temporary degradation, then we do:
def get_json():
if user_name == "user 001":
with urllib.request.urlopen(
"http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets?user_name=user&001",timeout=15) as url:
complete_data = json.loads(url.read().decode())
elif user_name == "user 002":
with urllib.request.urlopen(
"http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets?user_name=user&002",timeout=15) as url:
complete_data = json.loads(url.read().decode())
return complete_data
def get_tickets_not_temp_degradation(start_date,end_date,complete_):
return Counter([k['user_name'] for k in complete_data if start_date < dateutil.parser.parse(k.get('DateTime')) < end_date and k['T_subcategory'] != 'Temporary Degradation'])
Basically, we get the whole set of tickets from the current and last year, then we let Python to filter the complete set by user and so far there are only 10 users which means that this process is repeated 10 times and makes me no surprise to discover why we get the delay...
My questions is how can I fix this problem of the requests library? I am using the following link Requests library documentation as a tutorial to make it working but it just seems that my payload is not being read.
Your Postman request is a JSON body. Just reproduce that same body in Python. Your Python code is not sending JSON, nor is it sending the same data as your Postman sample.
For starters, sending a dictionary via the data arguments encodes that dictionary to application/x-www-form-urlencoded form, not JSON. Secondly, you appear to be sending a single filter.
The following code replicates your Postman post exactly:
import requests
filters = {"filter": {
"filters": [{
"field": "RCA_Assigned_Date",
"operator": "gte",
"value": "2017-05-31 00:00:00"
}, {
"field": "RCA_Assigned_Date",
"operator": "lte",
"value": "2017-06-04 00:00:00"
}, {
"field": "T_Subcategory",
"operator": "neq",
"value": "Temporary Degradation"
}, {
"field": "Issue_Status",
"operator": "neq",
"value": "Queued"
}],
"logic": "and"
}}
url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets"
response = requests.post(url, json=filters)
Note that filters is a Python data structure here, and that it is passed to the json keyword argument. Using the latter does two things:
Encode the Python data structure to JSON (producing the exact same JSON value as your raw Postman body value).
Set the Content-Type header to application/json (as you did in your Postman configuration by picking the JSON option in the dropdown menu after picking raw for the body).
requests is otherwise just an HTTP API, it can't make Cassandra do any more than any other HTTP library. The urllib.request.urlopen code sends GET requests, and are trivially translated to requests with:
def get_json():
url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets"
response = requests.get(url, params={'user_name': user}, timeout=15)
return response.json()
I removed the if branching and replaced that with using the params argument, which translates a dictionary of key-value pairs to a correctly encoded URL query (passing in the user name as the user_name key).
Note the json() call on the response; this takes care of decoding JSON data coming back from the server. This still takes long, you are not filtering the Cassandra data much here.
I would recommend using the json attribute instead of data. It handles the dumping for you.
import requests
data = {'user_name':'user&001'}
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets/"
r = requests.post(url, headers=headers, json=data)
Update, answer for question 3. Is there a reason you are using urllib? I’d use python requests as well for this request.
import requests
def get_json():
r = requests.get("http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets”, params={"user_name": user_name.replace(" ", "&")})
return r.json
# not sure what you’re doing here, more context/code example would help
def get_tickets_not_temp_degradation(start_date, end_date, complete_):
return Counter([k['user_name'] for k in complete_data if start_date < dateutil.parser.parse(k.get('DateTime')) < end_date and k['T_subcategory'] != 'Temporary Degradation'])
Also, is the username really supposed to be user+001 and not user&001 or user 001?
I think, you can use requests library as follows:
import requests
import json
payload = {'field':'T_Subcategory','operator':'neq','value':'Temporary Degradation'}
url = requests.post("http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets",data=json.dumps(payload))
You are sending user in url, use it through post, but its depend upon how end points are implemented. You can try the below code :
import requests
from json import dumps
data = {'user_name':'user&001'}
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
url = "http://10.61.202.98:8081/T/a/api/rows/cat/ect/tickets/"
r = requests.post(url, headers=headers, data=dumps(data))

Asana task creation missing fields error

I am trying to create Asana task using oAuth, so far it was working fine, but suddenly its not working anymore.
It is throwing back the following response:
{"errors":[{"message":"missing both `parent` and `workspace` fields; at least one required"}]}
Here is what I am doing
import requests
import json
data = {
'workspace':'<my workspace id>',
'assignee':'me',
'name':'My awesome task',
'notes':'My task notes'
}
headers ={'Authorization':'Bearer <my token>','Content-Type':'application/json'}
response = requests.post('https://app.asana.com/api/1.0/tasks',
headers=headers,
data=json.dumps(data))
print response.text
It looks like you're missing a data parameter in the payload. It's a common gotcha, but when you post JSON data to the API you need to send something that looks like this:
{
"data": {
"name": "This is my task",
"workspace": 1234,
...
}
}
In this case, you should be able to fix it by simply changing the last parameter to data=json.dumps({ 'data': data }).
Hope that helps!

Categories

Resources