-3

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*>

Jimmy
  • 1
  • 4

1 Answers1

0

There is no server running when you're trying to make your request. uvicorn is importing your code, and you're apparently trying to make a request while the code is being imported.

uvicorn can't launch the API and bind to the port before it has finished importing the code and the ASGI application has been set up and properly configured.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • I tried to move the request code after the line of uvicorn, but the result is the same and it appears the server has not fully launched yet.. any recommend solution such that I can send a request back to my own fastapi server? – Jimmy Jul 01 '22 at 09:25
  • That won't help, since the server won't have launched until after all the code has been parsed/imported/run. The question then usually becomes: why would you want to do that? What is the reason for having to make a request, instead of configuring whatever state you want internally as part of your application setup? – MatsLindh Jul 01 '22 at 09:29
  • I intend to run a function after the fastapi server start running for my own initialization of my program.. and the only way I can think of is to generate a request webhook for my server to receive it.. any smarter or direct solution? – Jimmy Jul 01 '22 at 10:03
  • 1
    You can use the events provided by FastAPI: https://fastapi.tiangolo.com/advanced/events/ - `@app.on_event("startup")` – MatsLindh Jul 01 '22 at 10:07
  • yes, i considered that but the server is not launched yet by that time, is it possible to trigger a function after the server is successfully launched? (because i want to utilise the background task function as well) – Jimmy Jul 01 '22 at 10:23
  • 1
    @Jimmy You might find [this answer](https://stackoverflow.com/a/70873984/17865804) helpful. – Chris Jul 01 '22 at 10:33
  • yes, it appears that threading allow me to wait for the server to start and run a request function with background task – Jimmy Jul 01 '22 at 12:02