How to access FastAPI backend from a different machine/IP on the same local network?

Make sure that the host flag is set to 0.0.0.0, when running the server— 0.0.0.0 means all IPv4 addresses on the local machine. If a host has two IP addresses, e.g., 192.168.10.2 and 10.1.2.5, and the server running on the host listens on 0.0.0.0, it will be reachable at both of those IPs. For example, through command line interface:

uvicorn main:app --host 0.0.0.0 --port 8000

or, programmatically:

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)

You may also need to adjust your Firewall to allow external access to the port you specified (by creating an inbound firewall rule for Python—on Windows, this is usually automatically created when allowing a program, Python in this case, to communicate through Windows Firewall, and by default this allows traffic on Any port for both TCP and UDP connections).

Additionally, if your frontend is running on a separate server from the backend, please make sure to have CORS enabled and properly configured, as desribed in this answer and this answer. For example:

origins = ['http://localhost:3000','http://192.168.178.23:3000']

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Finally, please take a look at this answer and this answer regarding using the proper origin/URL when issuing a fetch request from the frontend. In short, in your JavaScript asynchronous request, you should use the same domain name (but with the port number your backend server is listening on) used for accessing the frontend in the address bar of your browser, for example:

fetch('http://192.168.178.23:8000/people', {...

Otherwise, if the domain differs, it should then be added to the list of origins in the CORS settings of the backend. For convenience, you may want to use relative paths, as suggested in a linked answer above, if both backend and frontend servers are running on the same machine).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)