ESP8266 Connecting to WIFI and Making HTTP Requests using MicroPython

There are two WiFi interfaces, one for the station (when the ESP8266 connects to a router) and one for the access point (for other devices to connect to the ESP8266).

Here is an example to connect ESP8266 to your wifi router.

>>> import network
>>> sta_if = network.WLAN(network.STA_IF)
>>> sta_if.active() # check if station mode is activated or not.
False
>>> sta_if.active(True) # activate the station mode.
>>> sta_if.connect('<your ESSID>', '<your password>') # connect to ssid using password.
>>> sta_if.isconnected() # check if you are connected to the ssid.
>>> sta_if.ifconfig() # check the ip address of the ESP8266 module.
('192.168.0.2', '255.255.255.0', '192.168.0.1', '8.8.8.8')

You can create a function and use it in the code instead of writing all of these lines again and again.

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to network...')
        sta_if.active(True)
        sta_if.connect('<essid>', '<password>')
        while not sta_if.isconnected():
            pass
    print('network config:', sta_if.ifconfig())

Here is an example of http get request.

def http_get(url):
    _, _, host, path = url.split('/', 3) #get the domain name and rest of the url
    addr = socket.getaddrinfo(host, 80)[0][-1] #get address for the domain.
    s = socket.socket() # create a socket.
    s.connect(addr) # connect to the remote machine using that socket
    # make an http request.
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))

    while True:
        data = s.recv(100)# read the response, 100 bytes at a time.
        if data:
            print(str(data, 'utf8'), end='')
        else:
            break
    s.close()# close the socket.
Disclamer:

All of the above codes are directly taken from the official documentation of Esp8266 and micropython. To get the complete details about the topics, please refer following links