Requests: A Library for Simplifying HTTP Requests for Web Scraping and API Calls

Click 【Follow + Collect】 to get the latestpractical code examples

1. Sending a Simple GET Request

import requests

# Define the URL for the request
url = 'https://jsonplaceholder.typicode.com/posts/1'
# Send a GET request
response = requests.get(url)

# Check the response status code
if response.status_code == 200:
    # Print the JSON data from the response
    print(response.json())
else:
    print(f"Request failed, status code: {response.status_code}")

Knowledge Summary:

  • <span>requests.get()</span> is used to send an HTTP GET request.
  • <span>response.status_code</span> retrieves the response status code, where 200 indicates a successful request.
  • <span>response.json()</span> is used to parse the response content into JSON format, suitable for cases where the response is JSON data.

2. GET Request with Query Parameters

import requests

# Define the URL for the request
url = 'https://jsonplaceholder.typicode.com/posts'
# Define query parameters
params = {
    'userId': 1
}
# Send a GET request with query parameters
response = requests.get(url, params=params)

if response.status_code == 200:
    print(response.json())
else:
    print(f"Request failed, status code: {response.status_code}")

Knowledge Summary:

  • By using the <span>params</span> parameter, you can add query parameters to the GET request, and <span>requests</span> will automatically encode them into the URL.
  • Query parameters are commonly used for filtering, pagination, etc., making it easier to retrieve specific data from the server.

3. Sending a POST Request

import requests

# Define the URL for the request
url = 'https://jsonplaceholder.typicode.com/posts'
# Define the request body data
data = {
    'title': 'foo',
    'body': 'bar',
    'userId': 1
}
# Send a POST request
response = requests.post(url, json=data)

if response.status_code == 201:
    print(response.json())
else:
    print(f"Request failed, status code: {response.status_code}")

Knowledge Summary:

  • <span>requests.post()</span> is used to send an HTTP POST request.
  • <span>json</span> parameter is used to pass JSON formatted request body data, and <span>requests</span> will automatically set the request header’s <span>Content-Type</span> to <span>application/json</span>.
  • Status code 201 typically indicates that the resource was created successfully.

4. Sending a PUT Request

import requests

# Define the URL for the request
url = 'https://jsonplaceholder.typicode.com/posts/1'
# Define the request body data
data = {
    'title': 'updated title',
    'body': 'updated body',
    'userId': 1
}
# Send a PUT request
response = requests.put(url, json=data)

if response.status_code == 200:
    print(response.json())
else:
    print(f"Request failed, status code: {response.status_code}")

Knowledge Summary:

  • <span>requests.put()</span> is used to send an HTTP PUT request, typically for updating resources on the server.
  • Similar to POST requests, the request body data is passed using the <span>json</span> parameter.

5. Sending a DELETE Request

import requests

# Define the URL for the request
url = 'https://jsonplaceholder.typicode.com/posts/1'
# Send a DELETE request
response = requests.delete(url)

if response.status_code == 200:
    print("Resource deleted successfully")
else:
    print(f"Request failed, status code: {response.status_code}")

Knowledge Summary:

  • <span>requests.delete()</span> is used to send an HTTP DELETE request to remove resources from the server.
  • Typically, DELETE requests do not require a request body, only the URL of the resource to be deleted needs to be specified.

Summary of Knowledge Points and Code Features

Knowledge Point Description Code Features
Sending Requests Use the <span>requests</span> library’s <span>get()</span>, <span>post()</span>, <span>put()</span>, <span>delete()</span> methods to send different types of HTTP requests Method names are intuitive and easy to use
Status Code Check Check the response status of the request using <span>response.status_code</span> Convenient for determining if the request was successful
Data Transmission Use the <span>params</span> parameter to pass query parameters, and <span>json</span> parameter to pass JSON formatted request body data Automatically handles data encoding and request header settings
Response Handling <span>response.json()</span> is used to parse the JSON formatted response content Simplifies the data processing process

Click 【Follow + Collect】 to get the latest practical code examples

Python 20-day learning plan

7-day learning plan for Python

Python implementation similar to Postman calls

Python implementation of LAN file sharing tool

Python implementation of online calligraphy generator

Python implementation of leaf carving images

Python ID photo generator with multiple sizes

Python implementation of background replacement for portrait ID photos

Python development of custom EXE packaging program

Python implementation of seal generator

Python implementation of batch certificate production factory

Python one-click generation of leave request form with seal in Word

Python quick PS image color picker and other editors

Python implementation of batch certificate production factory

Python quick PS image color picker and other editors

Python implementation of custom color picker

Python implementation of automatic watercolor sketch

Python implementation of creative drawing board code

Using Python to create a Chinese character stroke query tool: from GUI interface to stroke animation implementation

Python implementation of meme maker

Python implementation of Chinese chess mini-game

Python implementation of seal generator

Python simulation of Kingsoft Typing Tutor

Python super practical Markdown to rich text tool – full code analysis

Python implementation of snake game source code analysis

Python implementation of QR code generation

Python implementation of video player

Python implementation of seal generator

Python implementation of online seal making

Python + AI to create a simple intelligent voice assistant

Python implementation of simple notepad

Python implementation of Markdown to HTML tool code

Python implementation of creative drawing board code

Python implementation of simple drawing tool code

Python implementation of video player

Python implementation of simple notepad

Python implementation of connect the dots game code analysis

Python implementation of simple computer process manager

A super practical tool in Python – word frequency statistics tool

Python simple weather crawler tool

Python scheduled task reminder tool

Python “Guess the Number Game Code Analysis”

Python “Simple Calculator Code Analysis”

Python + AI online document generation assistant

Python “Password Generator Code Analysis”

Python | + AI to create a simple intelligent voice assistant

Python implementation of simple drawing tool code

Python implementation of Markdown to HTML

Python implementation of video player

Python implementation of connect the dots game code analysis

Python implementation of volcano AI call to generate stories

Python implementation of Doubao AI call to generate stories

Python implementation of simple notepad

Python implementation of simple computer process manager

Practical 1

  1. Python: QR code generator

  2. Python-pgame implementation of maze

  3. Python – implementation of weather clock assistant

  4. Python – QrCode implementation of various QR codes

  5. Python-pyglet implementation of HarmonyOS clock

  6. Python-pickle parsing to get WeChat friend information

  7. Python-wxPy initial version implementation of WeChat message bombing

  8. Python implementation of gossip starry sky clock

  9. Python implementation of National Day red flag avatar effect

  10. Python-PIL implementation of adding icons to specified positions on images

Practical 2

  1. Python-wxPy initial version implementation of WeChat message bombing

  2. Python-PIL library Image class parsing

  3. Python-tlinter implementation of simple student management system

  4. Python-itChat implementation of WeChat message push

  5. Python implementation of Pdf to Word

  6. Python – implementation of automatic couplet generation assistant

  7. Py2Exe another way of packaging

  8. Python-tts generation voice conversion assistant

  9. python-win32 etc. implementation of exe auto-add to computer startup options

  10. python implementation of desktop video recording

  11. PySimpleGUI-checkbox Python implementation of image cropping into a grid

  12. python packaging into exe file

  13. Python-faker generating virtual data

  14. python implementation of player Python-FastApi simple implementation

  15. python crawling Douban movie reviews

  16. Python crawling public account article collection

Practical 3

  1. python implementation of simple flying flower order

  2. python – get the image for guessing idioms

  3. python-menu menu implementation

  4. Python-pySimpleGUI implementation of interface

  5. Python – color image conversion to outline

  6. Python-moviepy – implementation of audio and video player

  7. Python operating SQLite database

  8. Python-PySimpleGUI implementation of menu

  9. python-Tkinter implementation of personalized signature

  10. Python-WordCloud cloud word map

  11. Python-customTkinter usage

  12. Python-tkinter (down)

  13. Python-tkinter (middle)

  14. python-tkinter (1)

  15. Python implementation of video assistant

Practical 4

  1. Python implementation of video assistant

  2. Python-flask-1: building the main page

  3. Python ttkbootstrap interface

  4. python-PyQt5 implementation of image display and simple reader

  5. Configuring Qt Designer and Pyuic on Pycharm

  6. Python PIL implementation of cropping and generating images of one inch and two inches

  7. Python crawling Kingsoft dictionary query results

  8. python implementation of generating personalized QR codes

  9. AI human-computer battle version of Gomoku game (AI + pygame implementation)

  10. python implementation of garbage classification query tool

  11. python – implementation of menu

  12. Python application in the field: automated testing

  13. Python application in the field: web development

  14. Python application in the field: automated operations

Requests: A Library for Simplifying HTTP Requests for Web Scraping and API Calls

Requests: A Library for Simplifying HTTP Requests for Web Scraping and API Calls

Leave a Comment