I have been trying for ages and can't figure it out, I hope you can help me. I have my SQL database running as well as FastApi. FastAPI is running on: http://127.0.0.1:8000 <- as seen here
And it works perfectly when testing on OpenApi as shown here.
I have my flutter app making the the following get request:
Future MakeGetProductRequest() async {
Uri url = Uri.parse('http://localhost:8000/items?page=1&number=5');
var response = await http.get(url);
return response;
}
When running the app on a physical device through USB-debugging, I get the following Error:
Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 34214
Full console error here
NOTE: I am running this on a physical device not an emulator!
CodePudding user response:
It won't work on the loopback address. Your address 127.0.0.1 is not accessible on the flutter device.
To connect both of them, you will have to run FastAPI on 0.0.0.0 like this:
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
The above code will make your local IP available over the LAN. Just make sure your phone and PC are connected to the same WIFI network.
To get your PC's IP address, run this in command prompt:
ipconfig
And you will get output like this:
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 192.168.29.82
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.29.1
You can see my IPv4 Address
is 192.168.29.82
so, to access FastAPI from my flutter code, I will have to connect to http://192.168.29.82:8000