FastApi and HTTP header Authorization: Token, get error in use "authorization: token is an invalid header name" - python-3.x

I need use HTTP authorization with header Authorization: Token. My code:
#router.get('/versions',tags=["Credentials"],responses={
200: {
"model": List[models.versions_info],
"description": "Return has code",
"headers": {"Authorization": {"description":"Token party","type":"string"}}
}})
async def list_versions(token: Union[str, None] = Header(description="Token party",alias="Authorization: Token",default=None)):
out=[{"version": "2.1.1","url": "https://www.server.com/ocpi/2.1.1/"},{"version": "2.2","url": "https://www.server.com/ocpi/2.2/"}]
return Response(status_code=200,content=json.dumps(out), media_type="application/json", headers={"Authorization: Token "+config.globals["mytoken"]})
However, when using I get an error:
Can you tell me where I'm wrong?
Update: if i modify code to:
async def list_versions(token: Union[str, None] = Header(alias="Authorization",default=None))
the header is not sent at all:

Related

Swagger produces key behaving differently in Openapi 3

I'm currently converting my swagger file to openapi3 and I have an endpoint thats returning a json response and I am using produces to output it as text/plain. I know the produces key for responses has been replaced in openapi3 by content: text/plain: etc.. but this is no longer converting my response. So previously if I called response.text after calling the endpoint I would get "This is a test." but now I get '"This is a test."\n'
Swagger 2 file:
/api/logs:
get:
description: Retrieve logs .
operationId: controller.get_logs
responses:
"200":
description: Job logs found
schema:
type: string
produces:
- text/plain
Openapi 3 file:
/api/logs:
get:
description: Retrieve logs .
operationId: controller.get_logs
responses:
"200":
description: Job logs found
content:
text/plain:
schema:
type: string
Below is a snippet of the application code, we call an external API and just return the response from that call. I don't have a snippet of the Api code to share but I have added some logs to display the response content:
resp = job.get_output() # Api call
try:
json_resp = resp.json()
LOGGER.info(f"Response: {resp}")
LOGGER.info(f"JSON: {json_resp}")
LOGGER.info(f"Text: {repr(resp.text)}")
LOGGER.info(f"Headers: {dict(resp.headers)}")
except Exception as error:
return (
{
"message": f"Failed to get job output for job: {job_id}"
},
HTTPStatus.NOT_FOUND,
)
return json_resp, HTTPStatus.OK, dict(resp.headers)
Log output:
LOGGER - Response: <Response [200]>
LOGGER - JSON: This is a test.
LOGGER - Text: '"This is a test."\n'
LOGGER - Headers: {'Date': 'Tue, 28 Jul 2020 15:23:31 GMT', 'Content-Type': 'application/json', 'Content-Length': '18', 'Connection': 'keep-alive'}
What am I doing wrong or am I missing something?

Expected type object but found type string

I am having trouble with setting up my API. The error I am getting is as follows:
[
{
"message": "Wrong data in the response. ",
"error": [
{
"code": "INVALID_TYPE",
"params": [
"object",
"string"
],
"message": "Expected type object but found type string",
"path": "#/"
}
],
"content": "{\"success\":true,\"payload\":{\"userId\":47}}"
}
]
With response headers:
connection: keep-alive
content-length: 233
content-type: application/json; charset=utf-8
date: Fri, 17 Apr 2020 08:09:38 GMT
etag: W/"e9-2OFjPp0RZp8asoi4T2vo8yXiZxE"
x-powered-by: Express
Now I expected this to work, as this very same code worked when using Swagger 2.0 instead of the oas-tools 3.0.1. This is my swagger file:
openapi: 3.0.1
info:
title: Swagger test
version: 0.0.1
servers:
- url: http://localhost:8081/
paths:
/add-user:
post:
x-router-controller: 'addUser'
description: Adds a user to the database
operationId: add
requestBody:
$ref: '#/components/requestBodies/AddUser'
responses:
201:
description: Successfully added the user to the database
content:
application/json:
schema:
type: object
properties:
success:
type: boolean
payload:
type: object
properties:
userId:
type: integer
And this is my node script in which I send the response back:
db
.query(insert_user_query, [username, password])
.then(function(result) {
var response = {
"success": true,
"payload": {
"userId": result.rows[0].user_id
}
}
res.status(201).json(response)
})
Now I am completely lost, as I am building the JSON in the response variable, and I am setting response code 201 and sending it as json (which adds the application/json content-type), and yet Swagger interprets is as a string instead of an object.
Anyone here who could please point me in the right direction?
You have to take the string and parse it back into an object.
res.json() takes your object and converts it to a string using the json format. application/json is a string format and that's how you send javascript formatted objects over the network. They get converted to a canonical string format, sent over the network and then to use them as objects, they have to be parsed and converted back into real live objects.
You don't show your receiving code, but something on the receiving side needs to call JSON.parse() on the string response. That will return to you an actual object that you can use as it converts the json string back into an object on the receiving side.
I had the same problem and was using Express 4.x.
I could be mistaken, but I think there might be an issue with "res.json" (i.e. res.status(xxx).json({ a:b });)
I worked around the issue by using send:
res.status(201).send(response); // in your case

How to run REST API to build trigger in google cloud build

I have written a python script in my local machine and trying to run it and getting below error:
Error
{'error': {'code': 400,
'details': [{'#type': 'type.googleapis.com/google.rpc.Help',
'links': [{'description': 'Google developer console '
'API key',
'url': 'https://console.developers.google.com/project/[project_id]/apiui/credential'}]}],
'message': 'The API Key and the authentication credential are from '
'different projects.',
'status': 'INVALID_ARGUMENT'}}
python script to Build trigger
bashCommand = "gcloud auth print-access-token"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if error:
print(error)
headers = {
'Authorization' : 'Bearer '+str(output)[2:-3],
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
cloudbuild = {"build":
{"source":
{"repoSource":
{"projectId":"[PROJECT_ID]",
"repoName":"[repoName]",
"branchName":".*"
}
}
},
"description":"API TRigger for all branch",
"name":"[TRIGGER NAME]"
}
data = json.dumps(cloudbuild)
response = requests.post('https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/triggers?key=[API KEY]', headers=headers, data=data)
results_output = response.json()
pprint(results_output)
I also set the project in my local machine
gcloud config set project [project-name]
please give some solution for this.
Thanks in advance.
I removed API Key from request
Access-token is enough to run the above python script

Not able to upload file using slack api files.upload

This question may seem duplicate but I have tried a lot but did not get success.
I am trying to upload html file using https://slack.com/api/files.upload API but I am getting below error always.
response
{'ok': False, 'error': 'no_file_data'}
I went through documentation [a link]https://api.slack.com/methods/files.upload and tried with different options but still i am getting the same response {'ok': False, 'error': 'no_file_data'}
Also i have seen many similar questions in stack overflow but none of them resolved the problem.
[a link]no_file_data error when using Slack API upload
[a link]How to upload files to slack using file.upload and requests
Below is my code.
import requests
def post_reports_to_slack(html_report):
"""
"""
url = "https://slack.com/api/files.upload"
# my_file = {html_report, open(html_report, 'rb'), 'html'}
data = {
"token": bot_user_token,
"channels": channel_name,
"file": html_report,
"filetype": "html"
}
# data = "token=" + bot_user_token + \
# "&channels=" + channel_name +\
# "&file=" + html_report + "&filetype=" + "html"
response = requests.post(
url=url, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"})
print("response", response)
print(response.json())
if response.status_code == 200:
print("successfully completed post_reports_to_slack "
"and status code %s" % response.status_code)
else:
print("Failed to post report on slack channel "
"and status code %s" % response.status_code)
Please help to resolve the issue.
I was needed to add "content" argument and "filename" argument instead of "file" argument in files.upload API payload, Now file uploading to slack channel is working fine.
import requests
def post_reports_to_slack(html_report):
url = "https://slack.com/api/files.upload"
with open(html_report) as fh:
html_data = fh.read()
data = {
"token": bot_user_token,
"channels": "#channel_name",
"content": html_data,
"filename": "report.html",
"filetype": "html",
}
response = requests.post(
url=url, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"})
if response.status_code == 200:
print("successfully completed post_reports_to_slack "
"and status code %s" % response.status_code)
else:
print("Failed to post report on slack channel "
"and status code %s" % response.status_code)

Reqwest's Client.post() returning 400 bad request for File.io API

I'm learning Rust, and thought it would be handy to build a CLI to share files with the File.io API.
To do so, I am trying to use reqwest to send a request as described in the File.io docs:
# from file.io doc -> works fine
$ curl --data "text=this is a secret pw" https://file.io
> {"success":true,"key":"zX0Vko","link":"https://file.io/zX0Vko","expiry":"14 days"}
When I run the below code, I get a 400 response. Perhaps there's an issue with the headers? I've tried looking at the curl docs to find out what I could be missing, but I'm stumped.
Any help would be appreciated.
My code:
extern crate reqwest;
fn main() {
let client = reqwest::Client::new();
let res = client.post("https://file.io/")
.body("text=this is a practice run")
.send();
println!("{:?}", res);
}
Expected Response:
{"success":true,"key":"SOME_KEY","link":"SOME_LINK","expiry":"14 days"}
Actual Response:
Ok(Response { url: "https://file.io/", status: 400, headers: {"date": "Wed, 06 Feb 2019 03:40:35 GMT", "content-type": "application/json; charset=utf-8", "content-length": "64", "connection": "keep-alive", "x-powered-by": "Express", "x-ratelimit-limit": "5", "x-ratelimit-remaining": "4", "access-control-allow-origin": "*", "access-control-allow-headers": "Cache-Control,X-reqed-With,x-requested-with", "etag": "W/\"40-SEaBd3tIA9c06hg3p17dhWTvFz0\""} })
Your requests are not equivalent. curl --data means you're trying to send a HTML form with content type "x-www-form-urlencoded" or similar, whereas this line in your code
.body("text=this is a practice run")
means "just a text". You should use ReqwestBuilder::form as described here

Resources