fetching data from Flask REST service from laravel - python

I am trying to pass the path of an xml file to a flask/Python based REST-microservice. When passing the url manually to the service, it works as intended. However, I have problems calling the service from my laravel project.
Call to python rest service from laravel:
function gpxToJson(){
url = "http://127.0.0.1:5000/convert?path=C:/xampp/htdocs/greenlaneAdventures/public/storage/gpx/OOCe4r5Mas8w94uGgEb8qYlI0T3ClZDoclcfrR7s.xml" ;
fetch(url).then(function (response){
var track = JSON.parse(response.json());
return track;
});
}
Python script:
import gpxpy
import pandas as pd
from flask_cors import CORS
from flask import Flask, request, make_response, render_template
from flask_restful import Resource, Api
# create empty web-application
app = Flask(__name__)
api = Api(app)
CORS(app)
# create necessary classes
class Converter(Resource):
def get(self):
# path passed as argument
file = request.args.get('path', '')
# parse gpx file
gpx = gpxpy.parse(open(file))
# define data
track = gpx.tracks[0]
segment = track.segments[0]
# load wanted data into a panda dataframe
data = []
segment_length = segment.length_3d()
for point_idx, point in enumerate(segment.points):
data.append([point.longitude, point.latitude, point.elevation,
point.time, segment.get_speed(point_idx)])
columns = ['Longitude', 'Latitude', 'Altitude', 'Time', 'Speed']
gpx_df = pd.DataFrame(data, columns=columns)
# convert dataframe to json
gpx_json = gpx_df.to_json(orient='index')
print(gpx_json)
#return the converted json (http response code 200 = OK. The request has suceeded)
headers = {"Content-Type": "application/json"}
return make_response(gpx_json, 200, headers)
api.add_resource(Converter, "/convert")
#error handling
#app.errorhandler(404)
def not_found():
"""Page not found."""
return make_response(
render_template("404.html"),
404
)
#app.errorhandler(400)
def bad_request():
"""Bad request."""
return make_response(
render_template("400.html"),
400
)
#app.errorhandler(500)
def server_error():
"""Internal server error."""
return make_response(
render_template("500.html"),
500
)
#main function call
if __name__ == "__main__":
app.run(debug=True)
When calling the function gpxToJson() by submitting a form, I get the following error message in firefox.

Related

Get data from an API with Flask

I have a simple flask app, which is intended to make a request to an api and return data. Unfortunately, I can't share the details, so you can reproduce the error. The app looks like that:
from flask import Flask
import requests
import json
from requests.auth import HTTPBasicAuth
app = Flask(__name__)
#app.route("/")
def getData():
# define variables
username = "<username>"
password = "<password>"
headers = {"Authorization": "Basic"}
reqHeaders = {"Content-Type": "application/json"}
payload = json.dumps(
{
"jobType": "<jobType>",
"jobName": "<jobName>",
"startPeriod": "<startPeriod>",
"endPeriod": "<endPeriod>",
"importMode": "<importMode>",
"exportMode": "<exportMode>"
}
)
jobId = 7044
req = requests.get("<url>", auth=HTTPBasicAuth(username, password), headers=reqHeaders, data=payload)
return req.content
if __name__ == "__main__":
app.run()
However, when executed this returns error 500: Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
The same script but outside a flask app (just the function as it is defined here) runs with no problems at all.
What am I doing wrong?
flask app return format json. If you return req.content, it will break function. You must parse response request to json before return it.
from flask import jsonify
return jsonify(req.json())
It's better with safe load response when the request fail
req = requests.get()
if req.status_code !=200:
return {}
else:
return jsonify(req.json())

'message': 'The method is not allowed for the requested URL.'

I am getting this error when I run my python script to make a call to my API:
{'message': 'The method is not allowed for the requested URL.'}
I cannot figure out why I am getting this error as I am using the exact code as the tutorial I am following.
Here is the call to my API:
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.put(BASE + "video/1", {"likes": 10})
print(response.json())
And here is my API:
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
video_put_args = reqparse.RequestParser()
video_put_args.add_argument("name",type=str, help="t")
video_put_args.add_argument("views",type=int, help="t")
video_put_args.add_argument("likes",type=int, help="t")
videos = {}
class Video(Resource):
def get(self, video_id):
return videos[video_id]
def put(self, video_id):
args=video.args.parse_args()
return {videoid:args}
api.add_resource(Video, "/video/<int:video_id>")
if __name__ == "__main__":
app.run(debug=True)
Any help would be appreciated, thanks

How to make rest API that responds to post(data=data,header=header) with python and flask

I am trying to make a rest API in python.flask and I want it to be responsive to python.requests.post(data=data,header=header). But every tutorial and website only shows me Postman and
An API that responds to python.requests.post(PARAMS=data,header=header) but "PARAMS" does not work for my case. I've tried using python.flask.request.get_json(), I've tried using python.flask.Resource, I've tried using another one here:-
from flask import Flask
from flask_restful import Resource, Api, reqparse
from json import loads as dictionary
from flask import request as req
app = Flask(__name__)
api = Api(app)
#app.route('/test', methods=['POST'])
def post(username,token,url):
# gotit=dictionary(gotit)
k = '{"name":'+username+',"password":'+token+',"link":'+url+'}'
print(k)
return k
if __name__ == '__main__':
app.run()#debug=True)
But all in vain. Please help me make an API that responds to this:- python.requests.post(data=data,header=header). And also help with the header thing.
Python.v3.8
Here's your code but with some modification:
Server Code:
from flask import Flask, jsonify, request
import requests
import json
app = Flask(__name__)
#app.route('/test', methods=['POST'])
def post():
# you will get that data in request.data you can simplify/jsonfiy
text = str(request.data)
t = request.data
return t
if __name__ == "__main__":
app.run(debug=True)
python.requests Code:
import requests
header = {
"Content-Type":"text/plain"
}
data = {
"username":"myName",
"password":"myPass",
"url":"myWeb"
}
d = requests.post(url='http://127.0.0.1:5000/test', data=data, headers=header)
#
print(d.content)
Response from server something like this:
response Screenshot
I'm Using Python 3.9.1
Hope it will help You:)

How can I return API objects in application using flask

from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
#app.route('/address_search', methods=['GET'])
def sample():
zipcode = request.args.get('zipcode', None)
url = f'https://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}'
response = requests.get(url)
# results = response.json()
# results = jsonify(response) ?????
return response
if __name__ == '__main__':
app.run(debug=True)
I'm trying to create an Application which return the Address.
I succeeded to return url but about response, I can't and Internal Server Error appears
So I thought in flask, requests.get(url) cannot be used but I didn't came up an another way.
I heard that jsonify() is used but I don't known how.
I searched it in Google for two days but I still cannot find it's answer.
Someone please give me advice.
So, you want to return the response of that API in your web application, i guess this is what you're looking for?
#app.route('/address_search', methods=['GET'])
def sample():
zipcode = request.args.get('zipcode', None)
url = f'https://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}'
response = requests.get(url)
response_json = response.json()
return jsonify(response_json)
EDIT, response to your comment:
You can't do jsonify(response_json)['results'][0] because jsonify turns the JSON data to Flask Response object, instead try this:
#app.route('/address_search', methods=['GET'])
def sample():
zipcode = request.args.get('zipcode', None)
url = f'https://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}'
response = requests.get(url)
response_json = response.json()
results = response_json['results'][0]
return jsonify(results)

How can i build a proper restful response API by python flask for parameters

I'm studing about RESFful API with python.
I want to build a my restful api server,
but i have a problem,
i don't know how my api server returns proper data by reqeust each parameters
(request code sample)
the request code wants to get the information about 'item' : 'sword'
import requests
import json
url = "https://theURL"
querystring={"item":"sword"}
response = requests.request("GET", url, params=querystring)
print (response.json())
(API server response code sample, by flask python)
from flask import Flask, url_for
from flask_restful import Resource, Api, abort, reqparse
app = Flask(__name__)
api = Api(app)
TODOS = {
"version":"2.0",
"resultCode":"OK",
"output":{
{
"item" :"sword"
"price": 300,
"damage": 20,
},
{
"item" :"gun"
"price": 500,
"damage": 30,
},
},
}
class Todo(Resource):
def post(self):
return TODOS
api.add_resource(Todo, '/item.price')
if __name__ == "__main__":
app.run(debug=True, host ="192.168.0.8", port = 8080)
So i want to know how i use a code in response api server for returning 'item price' data by reqeusted parameters 'item : sword'
I just want to get the selected parameter's item price and damage information.
I thought it might be very easy, i'm tried to search the example but i couldn't find proper sample code.
I'm not a Flask-expert, but this helps setting up and running a minimalistic Flask-server. Then, this explains how to return json-formatted data from your server, and finally how to request and interpret the json-response can be found here. Summarized below:
Server returning a json-formatted data:
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def hello():
return "Hello, World!"
#app.route('/request_sword')
def grant_sword():
return jsonify({"sword": {"name":"Excalibur","price":"stack overflow"}})
Client requesting json-formatted data:
import json
import urllib.request
url = "http://127.0.0.1:5000/request_sword" ## My local host flask server
data = urllib.request.urlopen(url)
response = json.loads(data.read())
print(response)
That's all really. You may also just enter the url in your browser, which will correctly read the json-data:

Categories