python convert from request python to send api in json - python

guys I want to create a python API and request msg and get a response with JSON and send it to knime workflow and work with it
this is my script in python the fact is that he give me json.decoder.jsondecodeError
from importlib.metadata import files
import requests
url ='https://api.edination.com/v2/edifact/read'
headers = {'Ocp-Apim-Subscription-Key': '3ecf6b1c5cf34bd797a5f4c57951a1cf'}
files = {'file':open('C:\\Users\\hcharafeddine\\Desktop\\EDI\\Interchange_1654767219416.edi','rb')}
r = requests.post(url,files=files)
r.json()

We'll need more info to help further. I understand if you don't want to share the content of the EDI message, so here are a few things to try:
The EDINation website allows you to paste an EDI message in and it'll show you the JSON output that the API will return
It also has a sample EDIFACT document you can select and then save locally to run through your python script - you can then share the results here
You can also use HTTPToolkit to inspect the API request and response to troubleshoot further.

Related

Send POST request with Python that generates a download and download the file

There's a website that has a button which downloads an Excel file. After I click, it takes around 20 seconds for the server API to generate the file and send it back to my browser for download.
If I monitor the communication after I click the button, I can see how the browser sends a POST request to a server with a series of headers and form values.
Is there a way that I can simulate a similar POST request programmatically using Python, and retrieve the Excel file after the server sends it over?
Thank you in advance
The requests module is used for sending all kinds of request types.
requests.post sends the post requests synchronously.
The payload data can be set using data=
The response can be accessed using .content.
Be sure to check the .status_code and only save on a successful response code
Also note the use of "wb" inside open, because we want to save the file as a binary instead of text.
Example:
import requests
payload = {"dao":"SampleDAO",
"condigId": 1,
...}
r = requests.post("http://url.com/api", data=payload)
if r.status_code == 200:
with open("file.save","wb") as f:
f.write(r.content)
Requests Documentation
I guess You could similarly do this:
file_info = request.get(url)
with open('file_name.extension', 'wb') as file:
file.write(file_info.content)
I honestly do not know how to explain this tho since I have little understanding how it works

How to load json url and get data using python

I want to load this api url and fetch data. I am using this code to get this but i am getting 400 bad request.
Actual website link is (https://www.lffs.eu/les-clubs/)
'''
import urllib, json
enter code hereurl = "https://gestion.lffs.eu/lms_league_ws/public/api/v1/club/byMyLeague?filter=&club_status_id=1&page=2&pagination=21"
response = urllib.urlopen(url)
data = json.loads(response.read())
print(data)
'''
There is a problem with the way you used the API. If you run it on Google you will see the error. The API expects some kind of token from you. Make sure you provide it first.

Responding to an http request with JSON in Python

I have several Python scripts that are used from the CLI. Now I have been asked if I could provide a web API to perform some of the work normally done from the CLI. I would like to respond with JSON formatted data. I know little about JSON or API's.
How do I retrieve the query data from the http request?
How to a create the HTTP headers for the response from my script?
Given the following URL, how can I respond with a JSON reply of the name "Steve"?
http://myserver.com/api.py?query=who
I already have a functioning Apache web server running, and can serve up HTML and CGI scripts. It's simply coding the Python script that I need some help with. I would prefer not to use a framework, like Flask.
A simple code example would be appreciated.
The following is the Python code that I've come up with, but I know it's not the correct way to do this, and it doesn't use JSON:
#!/usr/local/bin/python3.7
import cgi # CGI module
# Set page headers and start page
print("Content-type: text/plain")
print("X-Content-Type-Options: nosniff\x0d\x0a\x0d\x0a")
# Form defaults
query_arg = None
# Get form values, if any
form = cgi.FieldStorage()
# Get the rest of the values if the form was submitted
if "query" in form.keys():
query_arg = form["query"].value
if query_arg == "who":
print("Steve", end="", flush=True)
You are trying to build a request handler with core python code. which is able to handle http request, In my opinion its not good idea as there are multiple securty scenarios attached with it, also in cross server request its bit difficult to handle all request and request scenarios . I will suggest to use Flask which is very lightweight and this will give an pre-setup of routing mechanism to handle all kind of request in very less code below is the snippet to generate http json response hope it helps
import sys
import flask
import random, string
from flask import jsonify
class Utils:
def make_response(self):
response = jsonify({
'message': 'success',
})
response.status_code = 200
return response

Error raised when trying to POST image to php using Requests

I am trying to upload a .jpg file to a server using HTTP POST with the requests library in Python 3.7.
Target URL has some PHP code that handles the upload, taking 'fileToUpload' as the multipart variable.
I tried putting the request into a with-statement, changing the data=files to files=files (as recommended by some example code), or setting the headers to multipart/form-data (which should not be necessary for this library)
import requests
url = 'http://someurl.com/upload/dir/post.php'
files = {'fileToUpload' : open('image.jpg', 'rb')}
r = requests.post(url, data=files)
If I run the script I raise every single error message in the post.php file, while if I take the thing to Insomnia or Postman the upload works just fine, so the server-side seems to be working.

Python script for upload to server

I am new to Python and it is first post. Want to upload a TXT file to server, (as of now, it is local host).Every time, I run the script, the local file uploaded and updated on server. I am using Requests module
import requests, time
url ='http://192.168.49.205/test/database/data.txt' # where i want to write
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
#r = requests.post(url,files=files) # this works too
r= requests.post('http://192.168.49.205/test/database/data.txt',
data={'upload_type': 'standard', 'upload_to': '0'},files=files)
print r.status_code
print r.text
data.txt is not updated. Just seeing old data (I put some values when file created).I am not using any Forms in PHP or HTML. Is it possible to upload with method?
Believe,I got some clarity after posting the question. Now, there is PHP file on server side listening to client. Here is the "post.php". So, this will replace the text file on Client side. PHP file get the Name, Task, Value from client and post to "a.txt" on server (local)
<?php
if(isset($_GET["Name"])){
$name=$_GET["Name"];
}
if(isset($_GET["Task"])){
$task=$_GET["Task"];
}
if(isset($_GET["Value"])){
$value=$_GET["Value"];
}
$f=fopen("a.txt","w") or exit("Unable to open file!");
fwrite($f,$name);
fwrite($f," ");
fwrite($f,$task);
fwrite($f," ");
fwrite($f,$value);
fclose($f);
?>`
So now Requests look like this
import requests, time
url = 'http://192.168.49.205/test/test.php'
post_data = {'Name':'job','Task':'008','Value':'8'}
r= requests.post('http://192.168.49.205/test/post.php', data= post_data)
print r.status_code
print r.text
Stil the values is not reaching "a.txt". What i am missing? Please advise!
You're not reading the files content in your code. The requests documentation states:
files – (optional) Dictionary of ‘name’: file-like-objects (or
{‘name’: (‘filename’, fileobj)}) for multipart encoding upload.
Your code suggests you want to use the second option. However:
files = {'file':('data.txt','C:\Python27\data.txt','rb')}
You're not creating the structure as the documentation indicates - you're passing a tuple of 3 strings instead of a tuple of (string, file_obj). You probably wanted to do this:
files = {'file':('data.txt',open('C:\Python27\data.txt','rb'))}

Categories

Resources