Python HTTP Methods Tutorial

Learn the most common HTTP Methods like GET, POST, PUT and DELETE with Requests library and Github API.

Python HTTP Methods Tutorial

In this article, we will focus on learning about the 4 common HTTP methods - GET, POST, PUT and DELETE.

You will learn about their properties and experiment with the Github API using python's Requests library to get a strong understanding of how these HTTP methods are used in real life projects.

đź’ˇ
If you prefer to watch videos over reading articles, check out this video or scroll to the bottom!

Contents of this article

  1. What is HTTP?
  2. GET Method and GET Request Example
  3. POST Method and POST Request Example
  4. PUT Method and PUT Request Example
  5. DELETE Method and DELETE Request Example
  6. Youtube Video

What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers by working as a response-request protocol.

Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response will contain the status information about the request and may also contain the requested content (if it is available).


GET Method and GET Request Example

The HTTP GET method is used to request a resource from the server. The GET request should only receive data. It shouldn’t change the state of the server.

If you want to change data on the server, use POST, PUT, PATCH or DELETE methods.

HTTP GET requests don’t have a message body. But you still can send data to the server using the URL parameters. However, that has a limitation of the maximum size of URL, which is about 2000 characters (depends on the browser).

The HTTP GET method is defined as idempotent, which means that multiple identical GET requests should have the same effect as a single GET request.

One way to demonstrate a GET request would be fetching the existing repositories from your Github account. You can find the documentation for the Github API here.

Before you start, you need to create a Personal Access Token in your Github settings. Once you have the token, create a .env file and store it.

# .env 
OAUTH_TOKEN="MY_PERSONAL_ACCESS_TOKEN"

You can use python’s dotenv library to use your environment variable in your code. This is the best practice for using environment variables as it keeps them secure.

Let’s go ahead and write our code to fetch all the repositories for our account on Github.

# Fetching Github repositories from an authenticated user
# Documentation - https://bit.ly/3qLu2sW

import requests as r
import json
import base64
from dotenv import load_dotenv
import os

load_dotenv()

oauth_token = os.getenv("OAUTH_TOKEN")

#Get all repositories from Github
base_url = "https://api.github.com/user/repos"
response = r.get(base_url,
           headers={'Authorization': 'token {}'.format(oauth_token)}
           )

for x in response.json():
    print(x["name"])

As you can see, we are passing our OAUTH_TOKEN in our headers in our GET request for authorization. This allows Github to verify our account and return the repositories that are present.

Important points about GET request

  1. GET requests can be cached
  2. GET requests remain in the browser history
  3. GET requests can be bookmarked
  4. GET requests should never be used when dealing with sensitive data

POST Method and POST Request Example

The HTTP POST method is used to create or add a resource on to the server. Unlike GET request, the POST requests may change the server state.

You can send data to the server in the body of the POST message. The type and size of data are not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields.

The HTTP POST requests can also send data to the server using the URL parameters. In this case, you are limited to the maximum size of the URL, which is about 2000 characters (it depends on the browser).

The HTTP POST method is not idempotent, which means that sending an identical POST request multiple times may additionally affect the state or cause further side effects.

One way to demonstrate a POST request would be creating a new repository in your Github account.

# Creating a new repository for an authenticated user
# Documentation - https://bit.ly/3oGRqpC

import requests as r
import json
import base64
from dotenv import load_dotenv
import os

load_dotenv()

oauth_token = os.getenv("OAUTH_TOKEN")

base_url = "https://api.github.com/user/repos"
repo_config = json.dumps({"name":"Http Methods Tutorial",
                          "auto_init": True,
                          "private": False,
                          "gitignore_template": "nanoc" })

response = r.post(base_url,
                  data = repo_config,
                  headers={'Authorization': 'token {}'.format(oauth_token)}
                  )
print(response.status_code)
print(response.json())

In the above code, I have created a variable called repo_config, which stores the information about my new repository in JSON format(Important). name is a required parameter for creating a new repository on Github. Rest of the parameters like auto_init, private and gitignore_template are not mandatory in your POST request.

If your request runs successfully, you get a response like this.

201
{'id': 320728459, 'node_id': 'xxxxxxxxxxyyyyyyyyyyzzzzz', 'name': 'Http-Methods-Tutorial', 'full_name': 'pylenin/Http-Methods-Tutorial', 'private': False, 'owner': {'login': 'pylenin', ... 'subscribers_count': 1}

Important points about POST request

  1. POST requests are never cached
  2. POST requests do not remain in the browser history
  3. POST requests cannot be bookmarked

PUT Method and PUT Request Example

While the POST method creates or adds a resource on the server,the HTTP PUT method is used to update an existing resource on the server. Unlike GET request, the HTTP PUT request may change the server state.

You can send data to the server in the body of the HTTP PUT request. The type and size of data are not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields. You can also post data to the server using URL parameters with a PUT request. In this case, you are limited to the maximum size of the URL, which is about 2000 characters (depends on the browser).

The HTTP PUT method is defined as idempotent, which means that multiple identical HTTP PUT requests should have the same effect as a single request.

Best way to demonstrate a PUT request would be to create a new file in your repository and then update the file.

We will first create a new file called hello.txt in our repository. According to Github API documentation, we have to pass in a commit message and the content of the file in base 64 encoding.

# Creating a new file in your repository
# Documentation - https://bit.ly/37bcjna

import requests as r
import json
import base64
from dotenv import load_dotenv
import os

load_dotenv()

oauth_token = os.getenv("OAUTH_TOKEN")

# Create a new file
base_url = "https://api.github.com/repos/pylenin/Http-Methods-Tutorial/contents/hello.txt"
base64_string = base64.b64encode(bytes("Hi there", 'utf-8'))
data = {"message":"Creating a new file",
        "content":base64_string.decode('utf-8')
        }

response = r.put(base_url,
           data = json.dumps(data),
           headers={'Authorization': 'token {}'.format(oauth_token)})

print(response.status_code)
print(response.json())

If the above code runs successfully, you should see your response like this.

201
{'content': {'name': 'hello.txt', 'path': 'hello.txt', 'sha': 'xxxYYYYZZZZ', ... 'signature': None, 'payload': None}}}

Notice how we receive a hash value(sha) in our response. That is the hash value of our commit. Further operations should always reference the hash value(sha) of their previous commits.

Once your hello.txt file is successfully created, let’s update the file. Currently, Hi there is the content in that file. For demonstration purpose, let’s change it Hi there ! Second time.

# Updating the contents of a file in your repository
# Documentation - https://bit.ly/37bcjna

import requests as r
import json
import base64
from dotenv import load_dotenv
import os

load_dotenv()

oauth_token = os.getenv("OAUTH_TOKEN")

# Updating the newly created file
base_url = "https://api.github.com/repos/pylenin/Http-Methods-Tutorial/contents/hello.txt"
base64_string = base64.b64encode(bytes("Hi there ! Second time", 'utf-8'))
data = {"message":"Creating a new file",
        "content":base64_string.decode('utf-8'),
        "sha":"xxxYYYYZZZZ"
        }

response = r.put(base_url,
           data = json.dumps(data),
           headers={'Authorization': 'token {}'.format(oauth_token)})
print(response.status_code)
print(response.json())

As you can see, we are also passing the hash key(sha) parameter in our json body this time. It references to the hash key(sha) value returned from our response from creating the hello.txt file.

If the above code runs successfully, you should see the response like this.

200
{'content': {'name': 'hello.txt', 'path': 'hello.txt', 'sha': 'abababccdd', ... 'signature': None, 'payload': None}}}

Important points about PUT request

  1. PUT requests are never cached
  2. PUT requests do not remain in the browser history
  3. PUT requests cannot be bookmarked

DELETE Method and DELETE Request Example

The HTTP DELETE method is used to delete a resource from a server. Unlike GET requests, the DELETE requests may change the state of a server.

If you send a message body on a DELETE request, it might cause some servers to reject the request. But you still have the option of sending data to the server using URL parameters.

The DELETE method is defined as idempotent, which means that multiple identical DELETE requests should have the same effect as a single request.

In order to demonstrate this method, let’s try to delete the hello.txt file. Based on the documentation, we have to mention a commit message and the hash key(sha) of the previous commit.

# Delete "hello.txt" file
# Documentation - https://bit.ly/3mi10xO

import requests as r
import json
import base64
from dotenv import load_dotenv
import os

load_dotenv()

oauth_token = os.getenv("OAUTH_TOKEN")

# Delete the file
base_url = "https://api.github.com/repos/pylenin/Http-Methods-Tutorial/contents/hello.txt"
data = {"message":"delete the file hello.txt",
        "sha":"abababccdd"}
response = r.delete(base_url,
           data = json.dumps(data),
           headers={'Authorization': 'token {}'.format(oauth_token)})
print(response.status_code)
print(response.json())

If the above code runs successfully, you should see your response like this.

200
{'content': None, 'commit': {'sha': 'abcxabcyabcz', 'node_id': 'MDY6Q29tbWl0MzIwNzI4NDU5OjRhZDA3NjA5ZTA4MGM0YmJlY2VjZDU0NTc0ZDY1MzkyYzg4ZDUzOTU=', ... 'signature': None, 'payload': None}}}

Youtube Video

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe