Odoo controllers avoid json-rpc when type="json" - odoo

I've the following route:
#http.route([
'/whatever/create'
], auth="none", type='json', methods=['POST'], csrf=False)
which I'm using to send a post request with json data on its body.
Is there any way to avoid using json-rpc responses on routes of type="json"? I would like to just answer plain json.
If it is not possible, is there any way to get the json data placed on the body request by using `type="http"?

#http.route('/whatever/create', auth='public', methods=['POST'], type='http')
def index(self, **kw):
data = request.httprequest.data
return 'success'
Above code defined in Odoo
url = "http://localhost:8069/whatever/create"
param = {
"type_operation": "PTI",
"label": "",
}
headers = {'Content-type': 'text/plain'}
r = requests.post(url, data=json.dumps(param), headers=headers)
Above code i have requested from a py file
While sending request you should change Content-type
'Content-type': 'application/json' --- > 'Content-type': 'text/plain'
Also while returning it only accept String
return {'status': 'success'} ---> return 'success'

Related

Podio API returning "unauthorized" response 401

I'm working on Podio API and as of now access API endpoints with the Python's (3.10.2) requests:
import requests as rq
def podio_api(url, payload=None, get=True):
"""Generic function to return responses from API,
it works with both GET and POST requests"""
url = "https://api.podio.com/" + url
headers = {
"Authorization": "OAuth2 " + get_token(),
"content-type": "application/json",
}
if get:
return rq.get(url, params=payload, headers=headers)
else:
return rq.post(url, json=payload, headers=headers)
The get_token() function successfully returns an access token (that's refreshed, so it's not expired). However, podio_api() started returning a 401 response ("unauthorized").
{'error_parameters': {}, 'error_detail': None, 'error_propagate': False, 'request': {'url': 'http://api.podio.com/app/<app_id>', 'query_string': '', 'method': 'GET'}, 'error_description': 'invalid_request', 'error': 'unauthorized'}
The app was working till yesterday.
Surprisingly, pypodio2 authorization works fine but I'd avoid it as it's an antique package.

missing keyword parameter is clearly included in api call

I'm trying to set up a basic API call to Amadeus. All the correct parameters are included and I'm grabbing a fresh token for each call.
It's a React/Flask application.
Here's my endpoint in app/routes.py:
#app.route('/search', methods=['GET'])
#cross_origin(origin='*')
def get_flights():
api_key = os.environ.get('amadeus_api_key', None)
api_secret = os.environ.get('amadeus_api_secret', None)
# first, you must get an access token using your Amadeus credentials
token_request = requests.post(
'https://test.api.amadeus.com/v1/security/oauth2/token',
data = {
'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': api_secret
}
)
token = token_request.json()['access_token']
bearer = 'Bearer {}'.format(token)
locations = requests.get(
'https://test.api.amadeus.com/v1/reference-data/locations',
headers = {
'Authorization': bearer
},
data = {
'subType': 'AIRPORT',
'keyword': 'BOS'
}
)
print(locations.json())
# example:
# https://test.api.amadeus.com/v1/reference-data/locations
# ?subType=AIRPORT&keyword=BOS
return jsonify({'token': token})
Here's the error:
{'errors': [{'status': 400, 'code': 32171, 'title': 'MANDATORY DATA MISSING', 'detail': 'Missing mandatory query parameter', 'source': {'parameter': 'keyword'}}]}
As you can see in the /search endpoint, the keyword parameter is clearly included.
What gives? Am I missing something?
The request to get the locations is not correctly built as it is sending subType and keyword as body instead of query parameters. According to requests documentation, you need to use params:
locations = requests.get(
'https://test.api.amadeus.com/v1/reference-data/locations',
headers = {
'Authorization': bearer
},
params = {
'subType': 'AIRPORT',
'keyword': 'BOS'
}
)

Why my request works with postman but not with vue.js axios?

I've made a back using Flask, and a front using vue.js,
Why I make the request with postman it returns what I want but not with axios ...
for exemple :
this.$axios
.post('http://127.0.0.1:5000/getUserDataByMail', { mail: 'test#test.com' })
.then(response => {
console.log('this.userData')
console.log(response.data)
this.userData = response
}
)
Is treated by :
#app.route('/getUserDataByMail', methods = ['GET', 'POST'])
def getUserDataByMail():
args = request.args
mail = args['mail']
return jsonify(mail)
cur = mysql.connection.cursor()
dataCur = cur.execute('select * from userdata where email like "' + mail + '"')
if dataCur > 0:
data = cur.fetchall()
cur.close()
return jsonify(data)
cur.close()
But this result in an error 400 ...
POSThttp://127.0.0.1:5000/getUserDataByMail [HTTP/1.0 400 BAD REQUEST 4ms]
Uncaught (in promise) Error: Request failed with status code 400
Help me I'm losing my mind ! (:
Axios by default posts an application/json request body.
To read JSON payloads in Flask, you use request.json
content = request.json
mail = content["mail"]
I can only assume Postman works because you were posting an application/x-www-form-urlencoded request body or using URL query parameters.
To match what you're doing in Axios, make sure you post JSON

ADF Create Pipeline Run - Parameters

I need to trigger a ADF Pipeline via REST API and pass a parameter in order to execute the pipeline for the given ID (parameter).
With sparse documentation around this, I am unable to figure out how to pass parameters to the URL
Sample:
https://management.azure.com/subscriptions/asdc57878-77fg-fb1e8-7b06-7b0698bfb1e8/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/df-datafactory-dev/pipelines/pl_StartProcessing/createRun?api-version=2018-06-01
I tried to send parmaters in the request body but I get the following message depending on how params are sent
{
"message": "The request entity's media type 'text/plain' is not supported for this resource."
}
I tried using python requests :
import requests
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01"
payload = " \"parameters\": {\r\n “stateID”: “78787878”\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer adsasdasdsad'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
I tried to put the parameter in the payload (body)
Paramters can be passed within body
python sample:
import requests
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01"
payload = "{\"stateID\":1200}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer adsasdasdsad'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
You have to use a parameter name as post
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01 -d '{"stateID"="78787878"}'
microsoft docs for your reference :
https://learn.microsoft.com/en-us/rest/api/datafactory/pipelines/create-run
You have to pass them as the POST body.
To pass more than one parameter the body this looks like:
{
"param1": "param1value"
,"param2":"param2value"
}

'Malformed or invalid request' with clarifai api

what is wrong with the following request for clarifai api-
import requests
image_url='https://samples.clarifai.com/food.jpg'
api='Key cb03ceba3c8842aeadd55dcb2f0be152'
headers = {
'Authorization': api,
'Content-Type': 'application/json',
}
data = '{"inputs": [{"data": {"image": {"url": image_url}}}]}'
url='https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs'
response = requests.post(url=url, headers=headers, data=data)
print(response.status_code, response.json())
i keep hitting this error-
400 {'status': {'code': 11102, 'description': 'Invalid request', 'details': 'Malformed or invalid request'}}
Looks like you need to use:
'{"inputs": [{"data": {"image": {"url": "' + image_url + '"}}}]}'
Since the single quotes are creating a string, you can't just add in a variable directly, but need to concatenate it. You were literally sending the text image_url and not the actual value of the variable image_url in that statement.
You need to correct the header as well to get a valid response
header = {'Authorization': 'Key '+ api_key ,"Content-Type": "application/json"}
you have to convert the data into JSON and json.dumps() will convert the data into JSON.
data = {"inputs": [{"data": {"image": {"url": image_url}}}]}
json_data = json.dumps(data)
I had the same problem; I solved it by converting the variable holding the image URL to a string. In your case, just make the following change:
data = '{"inputs": [{"data": {"image": {"url": image_url.tostring}}}]}'