Search code examples
pythonrestserverlocalhosttwisted

How i allow remote access to my python API?


I have built a python RESTful API which is using Klein/Twisted. Instead of using localhost I want to allow access to my public IP address, so everyone can connect to my API. (This is temporary for testing until I get it hosted on AWS EC2).

I have been very lost on how to do this and have followed tutorials such as forwarding port 80 but it doesn't seem to work. I do apologize if my knowledge is limited as I am not very proficient in this field. Could someone please point me to a resource?

This is the code I want to change to my public IP and port 80 so my API is accessible.

endpoint_description = "tcp:port=%s:interface=localhost" % 8090
endpoint = endpoints.serverFromString(reactor, endpoint_description)

Solution

  • The default for the IPv4/TCP and IPv6/TCP endpoints is to listen on all interfaces. All you have to do is not restrict it by specifying an interface:

    from twisted.internet.endpoints import TCP4ServerEndpoint
    from twisted.internet import reactor
    
    endpoint = TCP4ServerEndpoint(reactor, 8090)
    

    Notice also that there's no need to do string mashing in your example. Just instantiate the endpoint you want and pass it the arguments you want. The string syntax is for creating an endpoint from a description from a system that only supports strings (CLI, config files, etc).