I have error in the following code when I try to send a request with json data in it, is it because it only works synchronously, so does not work in fastapi which work asynchronously? If that is the case, what is the simplest way to send a request with json data in it?
import time
from fastapi import Request, FastAPI, BackgroundTasks
import multiprocessing as mp
import uvicorn
import requests
import json
def printmessage(job):
time.sleep(5)
print(job)
if __name__ == 'webhook_fastapi':
url = 'http://127.0.0.1:8000/webhook'
data = { 'text': 'hello'}
r = requests.post(url, data=json.dumps(data), headers={'Content-Type': 'application/json'})
print("Request Sent!")
app = FastAPI()
@app.post("/webhook")
async def webhook(request : Request, background_tasks: BackgroundTasks):
print("WEBHOOK RECEIVED")
job="doctor"
background_tasks.add_task(printmessage,job)
print('done')
return 'WEBHOOK RECEIVED'
if __name__ == '__main__':
print("PROGRAM LAUNCH...")
print("WEBHOOK RECEIVE READY...")
background_tasks = BackgroundTasks()
job="doctor"
background_tasks.add_task(printmessage,job)
uvicorn.run("webhook_fastapi:app", reload=False)
OUTPUT:
__main__
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
webhook_fastapi
Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 169, in _new_conn conn = connection.create_connection( File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection raise err File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1279, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1325, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1274, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1034, in _send_output self.send(msg) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 974, in send self.connect() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 200, in connect conn = self._new_conn() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 181, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0000013C0E494310>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 439, in send resp = conn.urlopen( File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen retries = retries.increment( File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\retry.py", line 574, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /webhook (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000013C0E494310>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "c:\Users*\webhook_fastapi.py", line 40, in uvicorn.run("webhook_fastapi:app", reload=False) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\uvicorn\main.py", line 463, in run server.run() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\uvicorn\server.py", line 60, in run return asyncio.run(self.serve(sockets=sockets)) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete return future.result() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\uvicorn\server.py", line 67, in serve config.load() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\uvicorn\config.py", line 458, in load self.loaded_app = import_from_string(self.app) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string module = importlib.import_module(module_str) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked
File "", line 850, in exec_module File "", line 228, in _call_with_frames_removed File "c:\Users*\webhook_fastapi.py", line 19, in r = requests.post(url, data=json.dumps(data), headers={'Content-Type': 'application/json'}) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 117, in post return request('post', url, data=data, json=json, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send r = adapter.send(request, kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /webhook (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000013C0E494310>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')) PS C:\Users*>