python for loop requests

Python for Loop Requests

Python is a popular programming language used in various applications. One of its most useful features is the for loop, which allows you to iterate over a sequence of values. When combined with the requests module, the for loop can become even more powerful. In this post, we will explore how to use a for loop with requests in Python.

Using a for loop with requests

The requests module allows you to send HTTP/1.1 requests easily in Python. To use a for loop with requests, first you need to import the module:


    import requests
  

Next, you can use a for loop to iterate over a list of URLs and send GET requests to each one:


    urls = ['https://www.google.com', 'https://www.facebook.com', 'https://www.twitter.com']

    for url in urls:
        response = requests.get(url)
        print(response.status_code)
  

In the code above, we define a list of URLs and then use a for loop to iterate over each one. We use the requests.get() function to send a GET request to each URL and save the response in a variable called response. Finally, we print the HTTP status code of each response using the status_code attribute.

Using a for loop with JSON data

The requests module also supports parsing JSON data from APIs. To use a for loop with JSON data, you can send a GET request to an API endpoint and then iterate over the JSON data using a for loop. Here is an example:


    import requests

    response = requests.get('https://api.github.com/users')
    data = response.json()

    for user in data:
        print(user['login'])
  

In the code above, we send a GET request to the /users endpoint of the GitHub API and save the response in a variable called response. We then use the json() method to parse the JSON data from the response and save it in a variable called data. Finally, we use a for loop to iterate over each user object in the JSON data and print their login username.