'How can i use the post api using pyodide

In pyodide, it is not support the requests module so to fetch the data from api we used open_url and how can we use the api for post the Data using pyodide



Solution 1:[1]

You can also use JS Fetch API direct form Python code. To do this, you first have to import window object from js module. Here is a live demo:

let python_code = `
from js import window

def fetch():
  window.fetch('http://karay.me/truepyxel/test.json').then(lambda resp: resp.json()).then(lambda jsoh: show_result(jsoh))
  
def show_result(data):
  div = window.document.createElement('div')
  #insert into body as a first child
  window.document.body.prepend(div)
  div.innerHTML=window.JSON.stringify(data)
`

// init environment
languagePluginLoader
// then run Python code
  .then(() => pyodide.runPythonAsync(python_code));
<!DOCTYPE html>
<html>
<head>
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
</head>
<body>
<button onclick='pyodide.globals.fetch()'>Fetch</button>
</body>
</html>

Solution 2:[2]

The requests module is currently not supported in pyodide because it relies on sockets which are not implemented in the WebAssembly browser VM.

You can however, make POST calls using Web APIs in pyodide. Below is an example using XMLHttpRequest

from js import XMLHttpRequest, Blob
import json

data = {"a": 1}

req = XMLHttpRequest.new()
req.open("POST", "https://httpbin.org/anything", False)
blob = Blob.new([json.dumps(data)], {type : 'application/json'})
req.send(blob)
str(req.response)

In the future it's possible that some of the classical HTTP client modules might be patched to use Web APIs in pyodide (cf pyodide#140).

Solution 3:[3]

As already mentioned we cannot use requests, so you can use javascript fetch to perform the POST operation, the sample snippet will work with pydiode and pyscript (async format), this same code can be written in sync-fashion using add_done_callback

import asyncio
from js import console, fetch

async def post_data():
    response = await fetch('http://example.com/test',{'method':'POST'})
    json = await response.json()
    console.log('json', json)
    return json

await post_data()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aray Karjauv
Solution 2 rth
Solution 3 Rajat Sahu