Character encoding-decoding json payload string in Requests HTTP library - json

I am using Requests HTTP library. I am trying to simple print HTML of the requested page.
Here is my payload string, I tried with decode('utf-8') but it doesn't work:
import json
import requests
url = "http://ec.europa.eu/eures/eures-searchengine/page/jvSearch/search?lang=de&app=1.3.1p1-build-0"
countryName = "ÖSTERREICH".decode('utf-8')
payload = '{"keywords":[{"keyword":"","specificSearchCode":"EVERYWHERE"}],"locationCriteriaBean":{"selectedNuts":[{"id":1231,"nutsCode":"AT","parentNutsId":None,"countryId":1,"label":"%s","nutsLevel":0,"regions":[]}],"notSpecifiedInCountry":[]},"selectedOccupations":[],"contractTypeCodes":[],"contractDurationCodes":[],"experienceCodes":[],"educationLevelCodes":[],"euresFlagCodes":[],"page":1,"resultsPerPage":50,"publicationDate":"LAST_MONTH","sortSearch":"REPLICATION_DATE_DESCENDING"}'% countryName
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print r.status_code
I am getting 500. Can some one tell me what should I do for that?

Related

json dictionary TypeError: string indices must be integers

import requests
url = "**************"
querystring = {"domain":"gmail.com","username":"random","server":"server-1","type":"real"}
headers = {
"X-RapidAPI-Key": "******************",
"X-RapidAPI-Host": "*****************"
}
response = requests.request("GET", url, headers=headers, params=querystring).text
response:
{"code":200,"msg":"OK","items":{"email":"vinhvivyanvinh72943#gmail.com","timestamp":1659215390}}
.
print(response['items'])
TypeError: string indices must be integers
Hello,
I do not encounter any problems when I use it in another dictionary.
How can I get email and timestamp into variables?
Use .json() on request response:
response = requests.request(
"GET", url, headers=headers, params=querystring
).json() # <-- note the .json()
print(response["items"]["email"], response["items"]["timestamp"])

Python AWS lambda JSON serialization issue

I am currently writing the aws lambda function with python to http post requests
apprantly its failing to serialize json headers
here my mode
import json
from botocore.vendored import requests
API_ENDPOINT = "https://api.someservices.com/v1/aws_accounts"
API_KEY = "asdfasdfasdfasdfasdf"
externalID ="dadsfasdfasdfasd"
def api_post(account_id, rolearn, account_name):
headers = {"Content-Type" : "application/json", "api_key" : API_KEY}
data = {"name":account_name,"authentication":{"protocol": "assume_role","assume_role_arn":rolearn,"assume_role_external_id":externalID}}
json_data = json.dumps(data)
response = requests.post(url = API_ENDPOINT,headers=headers, data=json_data)
print(response)
return response
this is the error I am getting
def lambda_handler(event, context):
result = update_ch(event['account_id'],event['rolearn'],event['account_name'])
return result
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: is not JSON serializable
This issue has been sorted out . I was using wrong library

Could not decode token: The token ###

I'm using Laravel 5.3 as an API for my iOS app. When I try to make HTTP calls with headers and parameters I get this 401 error:
message = "Could not decode token: The token
\"Optional(\""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhcL3Bvc3RMb2dpbiIsImlhdCI6MTQ4MDUzNzQxOCwiZXhwIjoxNDgwNTQxMDE4LCJuYmYiOjE0ODA1Mzc0MTgsImp0aSI6ImMyZmYxNzI5N2U5OGU4MzkzYzZkZWRmNTZlN2ZkMzNkIn0.u6sQqlq5k-B5jhZ7EymkXLlcTIQ-i7X_83an5irwTss\"" is an
invalid JWS";
"status_code" = 401; }
This is the code that makes the HTTP request:
let headers = ["Authorization":"Bearer \(token)"]
request(url! , method: .get, parameters: nil, encoding: JSONEncoding.default , headers: headers )
.responseJSON { response in
print("RESPONSE \(response)")
I did some googling and found a package to encode JWT called JWTDecode.swift. Here is the link to the code: https://github.com/auth0/JWTDecode.swift. I still couldn't figure out how to solve this issue.
change
let headers = ["Authorization":"Bearer \(token)"]
to something like
guard let token = token else { return }
let headers = ["Authorization":"Bearer \(token)"]
otherwise you are sending Optional(<token>) instead of <token>.

Grails: Error when fetching and parsing JSON

I have a Grails service that sends a request to the JIRA REST API and returns JSON - When I try to use JsonSlurper to parse the JSON, I get the following error:
ERROR errors.GrailsExceptionResolver - JsonException occurred when processing request: [GET] /osmDash/jira/storyComplete
Lexing failed on line: 1, column: 1, while reading 'j', no possible valid JSON value or punctuation could be recognized.
Here is the code in the controller:
def jsonFile = jiraService.fetchJQL('issuetype=Story AND status in (Resolved,Closed,Done) AND resolved>=-30d') as JSON
def jiraSlurper = new JsonSlurper()
def jiraResult = jiraSlurper.parseText('jsonFile').total
And this is what the JSON looks like when I render it in the page:
{"total":1356,"issues":[],"startAt":0,"maxResults":0}
I was looking at groovy.json.JsonSlurper parse JSON, which seems simliar, but I couldn't get this method to work. I'm looking specifically to assign the "total" value to a variable.
This is the service that is returning the JSON:
def fetchJQL(String jql, Integer maxResults = 0, def fields = null) {
jira.request(POST, JSON) { req ->
uri.path = '/rest/api/2/search'
headers.'Authorization' = authHash
body = [jql: jql, maxResults: maxResults, fields: fields]
response.success = { resp, json ->
return json
}
response.failure = { resp ->
println resp.statusLine.statusCode
println resp.statusLine
}
}

HttpBuilder accessing secured link https

I am using this code for GETting a JSON object from the URL using Groovy: the URL that I use is a HTTPS URL so when I test the code I get a 403 error, after Google it I understand that I need to use a HttpBuilder SSL but I don't understand how can I do it.
the code is :
def getJson(Integer id) {
def adress = new HTTPBuilder("https://api.XXXY.com")
def path="/vls/v1/etudiants/${id}?b=my&apiKey=99990"
//Get request
adresseServeur.request(Method.GET, JSON) {
uri.path = path
headers.Accept = 'application/json'
// success response handler
response.success = { resp, json ->
retourJson = json
}
// failure response handler
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"