How to call JDoodle API from Python/Flask app - python

I'm a student, and I'm looking for help calling Jdoodle's compiler API (docs here), please.
When I make a post request through Postman and use this as the JSON body, it works...
{
"script": "console.log('hello world')",
"stdin": "",
"language": "nodejs",
"versionIndex": "0",
"clientId": "a3462eccc82ecc57a745a23e52c5c71e",
"clientSecret": "another long string"
}
...and I get the output I expect:
{
"output": "hello world\n",
"statusCode": 200,
"memory": "22764",
"cpuTime": "0.05"
}
However, I can't get it to work from my Python Flask back-end. Here is my code:
#app_bp.route("/compile", methods=["POST"])
def compile():
path = "https://api.jdoodle.com/v1/execute"
query_params = {
"script": "console.log('hello world')",
"stdin": "",
"language": "nodejs",
"versionIndex": "0",
"clientId": "a3462eccc82ecc57a745a23e52c5c71e",
"clientSecret": "another long string here similar to one above"
}
response = requests.post(path, params=query_params)
return response.json()
I've also tried this by passing in headers (headers = {"Content-Type" : "application/json"}), and I still get the same response from Postman:
{
"error": "Invalid Request",
"statusCode": 400
}
I'm a newbie, and any help would be greatly appreciated. Thank you!

Related

Creating Jira issue with REST API

Having issues with trying to create an issue with Jira through the APIs, below is a sample of my code. We are using enterprise jira, I have to replace certain sections with so I hope it wont effect your ability to provide help.
from requests.auth import HTTPBasicAuth
import requests
user = '<ID>'
password = '<password>'
url = 'https://<enterprise>jira.<domain>.com/projects/<MYKEY>/rest/api/3/issue'
headers = {
'Content-Type': 'application/json',
}
json_data = {
"fields": {
"project": {
"key": "<MYKEY>"
},
"summary": "Creating From Collection",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "This is an autogenerated issue from a demo."
}
]
}
]
},
"issuetype": {
"name": "Task"
}
}
}
response = requests.post(
url,
headers=headers,
json=json_data,
verify=False,
auth=(user, password),
)
I get error code 405 and the following message when running print(response.text):
<!doctype html>HTTP Status 405 – Method Not Allowedbody {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 405 – Method Not AllowedType Status ReportMessage HTTP method POST is not supported by this URLDescription The method received in the request-line is known by the origin server but not supported by the target resource.Apache Tomcat/8.5.78
Im sure I'm doing something wrong so any help will be appreciated.
Also I have verified I have the right access by manually going to the project and creating an issue.
Your URL is wrong. For creating a Jira issue you want to use the create issue endpoint.
For server/datacenter:
url = 'https://<enterprise>jira.<domain>.com/rest/api/2/issue'
For cloud:
url = 'https://<enterprise>jira.<domain>.com/rest/api/3/issue'
You need to use a POST request to either of these endpoints.

Elastic search Api

Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kinesis*/_search"
payload = json.dumps(payload)
print(type(payload))
headers = {
'Content-Type': 'application/json',
}
result = requests.get(url=url,data=payload,headers=headers,auth=("test#example.com","*"))
print(result.json())
and getting the following error
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
I am Basic Auth .i.e. passing username and password for authorization.
Can somebody help me ?
In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.
e.g.
https://username:password#URL
https://admin:admin#www.the-internet.herokuapp.com/basic_auth

Python POST requests returns a "bad requests" when using a proxy

I have been testing things out using this proxy to scrape some Yelp pages. Things have been great but I had to use it for a POST request but I kept getting a 400 status code (Bad request). Here is the thing if I try it without the proxy I get the expected results.
Below is the code without using the proxy
import requests
import json
# Build a suitable JSON request for the required information
json_post = [
{
"operationName": "GetBusinessAttributes",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "35e0950cee1029aa00eef5180adb55af33a0217c64f379d778083eb4d1c805e7"
}
},
{
"operationName": "GetBizPageProperties",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "f06d155f02e55e7aadb01d6469e34d4bad301f14b6e0eba92a31e635694ebc21"
}
},
]
r = requests.post("https://www.yelp.com/gql/batch", json=json_post)
and here is the code with the proxy
import requests
import json
# Build a suitable JSON request for the required information
json_post = [
{
"operationName": "GetBusinessAttributes",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "35e0950cee1029aa00eef5180adb55af33a0217c64f379d778083eb4d1c805e7"
}
},
{
"operationName": "GetBizPageProperties",
"variables": {
"BizEncId": "1IMivcKgsN8xUL5dFKQK3w"
},
"extensions": {
"documentId": "f06d155f02e55e7aadb01d6469e34d4bad301f14b6e0eba92a31e635694ebc21"
}
},
]
r = requests.post("http://api.proxiesapi.com/?auth_key=d325db3f85a49b0561aaa0dda5209b15_sr98766_ooPq87&url=https://www.yelp.com/gql/batch", json=json_post)
I've included the auth_key so you can try it out. I have a feeling the problem in how I am passing the json. Any help will be much appreciated.

Python flask API POST request - JSON data after key

I'm very new to development, I'm writing a Python Flask app which is executing a POST request to log a new ticket on a system, I just need someone to verify how I structure this request as I'm really not sure.
The documentation says, for example:
curl api/v3/requests
-X POST
-H "Accept: application/vnd.manageengine.sdp.v3+json"
-H "Authorization: Zoho-Oauthtoken 1000.7xxx98976ab0xxxxxx19901e7551be57.bxxxx921ed64c04f79622bebcfxxxxxx"
-H "Content-Type: application/x-www-form-urlencoded"
-d input_data= '{
"request": {
"subject": "Need an External Monitor",
"resolution": {
"add_to_linked_requests": false,
"content": "The following is the resolution to the above request"
}
}
It's expecting input_data key, followed by the JSON array of info to submit.
The documentation is (here)
My code:
#app.route("/log", methods=["GET"])
def log():
"""Fetching a protected resource using an OAuth 2 token.
"""
servicedesk = OAuth2Session(client_id, token=session['oauth_token'])
headers = {"Authorization": "Bearer " + token, "Accept": "application/vnd.manageengine.sdp.v3+json", "Content-Type": "application/x-www-form-urlencoded"}
data = {
"request": {
"subject": "New Incident",
"mode": {
"name": "E-Mail",
},
"group": {
"name": "Incident"
},
"requester": {
"name": "Sarah Curtis Test"
},
"status": {
"name": "Open",
},
"template": {
"name": "Report an Incident"
},
"request_type": {
"name": "Incident",
},
"description": "This is a test. please ignore",
"category": {
"name": "Incident"
}
}
}
requests.post('https://sdpondemand.manageengine.eu/api/v3/requests?input_data=', data=data, headers=headers)
I don't have access to logs on the server to see what it is receiving either as it's a cloud service (unless there's a way to echo back the original raw POST request?)
The ticket isn't being logged when I try and do so via my app. It does work through Postman app to test the API request, when I add the JSON above into the x-www-form-urlencoded section on the body tab and put input_data into the key.
I need to know how to structure the POST request in my code. Any help appreciated! Thanks

JSON Parsing issue - Python

So i have build a REST Client that returns JSON response. However, i have an issue, where the JSON output is not exactly what i need:
Current Response:
{
"output": {
"status": "Device 'Test' does not exist",
"result": "null",
"response": {
"output": "success",
"result": 204
}
}
}
This output has an outermost enclosing "output" key, but i don't want that to be present. So basically i want my response to look like below:
{
"status": "Device 'Test' does not exist",
"result": "null",
"response": {
"output": "success",
"result": 204
}
}
I did try converting the JSON to Dict and then remove it, but no luck? any suggestions how to achieve this?
Thank you
if your response is already a dictionary or a json object then you can do following
value_required = response["output"]
if it is in text format (which I think it is) then you just need to do the following
import json
value_required = json.loads(response)["output"]
You should be able to do:
response = json.loads(response)['output']

Categories