HTTP requests

HTTP

HTTP stands for Hypertext Transfer Protocol. It is a protocol used while transferring web resources such as HTML documents, images, styles, and other files.

HTTP is a request response-based protocol. A web browser or client sends an HTTP request to a server and the web server sends the HTTP response back to the browser.

HTTP Request

A HTTP request consists of a method, path, version, and headers.

  • method :
  • path :
  • version :
  • headers :

HTTP Method

HTTP method describes the type of action that the client wants to perform and it communicates it to the server.

The primary or the most commonly used HTTP methods are GET, POST, PUT, and DELETE.

GET

The GET method is used to retrieve information from the given server.

POST

The POST request is used to send data to the server.

PUT

The PUT method updates whatever currently exists on the web server with something else.

DELETE

The DELETE method removes the resource.

Path

The path is the representation of where the resource is stored on the web server.

Version

There are multiple versions of the HTTP protocol. You want to explore these right now, but be aware that versions 1.1 and 2.0 are the most used.

Headers

Headers contain additional information about the request and the client that is making the request. Headers can contain information such as the server name, the server port, the request method type, and the content type.

The contents of the header can depend on the specific client and server, but these are some of the most common.

Body

For certain request methods, the request will also contain a body of content that the client is sending.

HTTP Response

HTTP responses follow a format similar to the request format. Following the header, the response will optionally contain a message body consisting of the response content, such as the HTML document, the image file, and so forth.

Status Code

HTTP status codes contained within the header indicate if the HTTP request successfully completed.

The code values are in the range of 100-599 and are grouped by purpose. The status message is a text representation of the status code.

Status code groups

There are five groups of status codes. They are grouped by the first stages of the error number.

  • informational is grouped from 100-199
  • successful responses are from 200-299
  • redirection messages are from 300-399
  • client error responses range from 400-499
  • server error responses are 500-599
Informational

Informational responses are provisional responses sent by the server. These responses are interim before the actual response. The most common informational response is 100, CONTINUE, which indicates that the web client should continue the request or ignore the response if the request is already finished.

Successful

Successful responses indicate that the request was successfully processed by the web server, with the most common success response being 200 OK.

You’re receiving these responses every day when you receive contents successfully from a website. The meaning of OK depends on the HTTP method. If the method is GET it means that the resource was found and is included in the body of the HTTP response, if it’s POST it means the resource was successfully transmitted to the web server, and if it’s PUT the resource was successfully transmitted to the web server. Finally, if the method is DELETE, it means the resource was deleted.

Redirection

Redirection responses indicate to the web client that the requested resource has been moved to a different path. The most common response codes used are 301 Moved Permanently and 302 Found.

The difference between the redirection messages through 301 and 302 is that 302 indicates a temporary redirection, the resource has been temporarily moved. When web browsers receive these responses, they will automatically submit the request for the resource at the new path.

Client Error

Client error responses indicate that the request contained bad syntax or content or cannot be processed by the web server.

  • 400 is used when the web browser or client submitted bad data to the web server.
  • 401 is used to indicate that the user must log into an account before the request can be processed.
  • 403 is used to indicate that the request was valid, but that the web server is refusing to process it. This is often used to indicate that a user does not have sufficient permissions to execute an action in a web application.
  • 404 is used to indicate that the request resource was not found on the web server.
Server Error

Server error responses indicate that a failure occurred on the web server while trying to process the request. The most common code used is 500 internal server error, which is a generic error status indicating that the server failed to process the request.

HTTPS

HTTPS is the secure version of HTTP. It is used for secure communication between two computers so that nobody else can see the information being sent and received.

It does this by using something called encryption. Like in HTTP, the requests and responses still behave the same way and to have the same content. The big difference is that before the content is sent, it is turned into a secret code. Only the other computer can turn the secret code back into its original content. If someone else was to look at the code, it wouldn’t be understandable.

Summary

Firstly, it is a protocol used by web clients and web servers. It works to transfer web resources such as HTML files and is the foundation of any data exchanges on the web. Also, remember that by using HTTPS, we send the information securely.

Requests are sent by the client, usually a web browser, and the server replies with responses which may be the return of an image, our HTML page. HTTP requests have syntax that includes, method, path, version, and headers.

HTTP responses follow a similar format to the request. An HTTP status codes indicates whether the HTTP request successfully completed.

The status code is a three-digit number that corresponds with groups representing different types of results.


Request and Response Objects

A web application works on the principle of a request-response cycle in a client-server architecture, following the HTTP protocol.

Generally, a browser sends the request in the form of a URL. The web application forms a suitable response to the data contained in the request.

This Reading will provide more detailed information on the Request and Response Objects.

Django handles the request and response with the help of HttpRequest and HttpResponse classes in the django.http module. 

Django obtains the HttpRequest object from the context provided by the server. 

As a client request is received, Django’s URL dispatcher mechanism invokes a view that matches the URL pattern and passes this HTTPRequest object as the first argument so that all the request metadata is available to the view for processing.

HttpRequest Object

The request object is characterized by its attributes and methods. They are used extensively in the processing logic of a Django view.

request.method

The view logic uses this attribute to identify how the client has approached the server. A browser submits its request using any HTTP methods or verbs – POST, GET, DELETE, and PUT.

Inside the view function, different conditional blocks may be executed depending on the value of the method attribute. For example:

if request.method == 'GET': 
    do_something() 
elif request.method == 'POST': 
    do_something_else() 

According to the REST(Representational State Transfer) principle, the POST method creates a new resource on the server. 

To fetch one or more resources from the server, the GET method is used. Similarly, the PUT method is for updating an existing resource, and the DELETE method is used to remove a resource from the server.

  • request.GET and request.POST

The attributes return a dictionary-like object containing GET and POST parameters, respectively. 

  • request.COOKIES

Along with the parameters, the browser also packs the request objects with cookies inserted by the server’s previous interactions. It is a dictionary of string keys and values.

  • request.FILES

When the user uploads one or more files with a multipart form, they are present in this attribute in the form of UploadedFile objects. By appropriate logic in the view, these uploaded files are saved in the designated folder on the server.

  • request.user

The request object also contains information about the current user. This attribute is an object of django.contrib.auth.models.User class. However, if the user is unauthenticated, it returns AnonymousUser. Inside the view, you can lay down separated separate logic for either of them.

if request.user.is_authenticated(): 
    # Do something for logged-in users. 
else: 
    # Do something for anonymous users. 
  • request.has_key()

This is a method available to the request object. It helps check whether the GET or POST parameter dictionary has a value for the given key.

Unlike the HttpRequest object, which is supplied by the server’s context, the response object of HttpResponse class is instantiated inside the view function before it is returned to the client. For example:

from django.http import HttpResponse 
def index(request): 
    return HttpResponse("Hello World") 

Although it is possible to render a hardcoded HTML string as the response, Django offers a better alternative to render a template web page.

from django.http import HttpResponse 
from django.template import loader 
def index(request): 
    template = loader.get_template('demoapp/index.html') 
    context={}  
    return HttpResponse(template.render(context, request)) 

You can pack additional headers or cookies in the response object.

HttpResponseObject

Some of the main attributes and methods of the HttpResponse object are:

  • status_code: returns the HTTP status code corresponding to the response
  • content: returns the byte string of the response.
  •  __getitem__(): method that returns the value of a header
  •  __setitem__(): method used to add a header
  • write(): This method creates a file-like object.

The following example demonstrates the attributes of the request and response objects. Add the following view function in views.py of the Django app.

from django.http import HttpResponse 
def index(request): 
    path = request.path 
    method = request.method 
    content=''' 
<center><h2>Testing Django Request Response Objects</h2> 
<p>Request path : " {}</p> 
<p>Request Method :{}</p></center> 
'''.format(path, method) 
    return HttpResponse(content) 

Start the server and check the response for http://localhost:8000/demo/  as the URL.

In this Reading, you explored the properties of the HttpRequest and HttpResponse objects.


Creating Requests and Responses

Request Response cycle in django

The cycle begins when the user enters a URL in their web browser. This URL is sent to the web server where Django searches for a match inside the urls.py file. Once it finds the URL, it is mapped to its associated view. Inside the view file, the view function receives the HTTP request as a request object. The view function then defines the appropriate HttpResponse and sends it back as a HttpResponse object. This response is processed by Django and the client receives the HttpResponse.

NOTE

Recall that Django uses the request and response objects to pass through the system.


Understanding URLs

Every single resource on the web is located by an address known as the uniform resource locator or URL.

A URL is made up of multiple parts put together. The first part is known as the scheme. This is followed by the domain name, the file path and parameters.

Scheme

The first part of A URL Is the scheme or otherwise referred to as the protocol. It’s located at the beginning of any ural address and can be identified as HTTP or HTTPS.

The characters HTTP stands for hypertext transfer protocol. The protocol determines the set of rules around the transmission and exchange of data. The difference between HTTP and HTTPS is security as the S stands for secure.

HTTP sends data as plain text which can expose the sender’s information HTTPS encrypts all data. This means the data isn’t in a readable format which is more secure.

The HTTP protocol is also responsible for sending and receiving HTML across the web. HTTP and its extension HTTPS is the most widely used protocol over the web.

Sub domain

The sub domain is located before the domain and usually contains the home page and other important pages.

The most common sub domain is World Wide Web represented by WWW. It’s important to know that some browsers replace the scheme and sub domain with a symbol such as that of a lock for encrypted pages. This is done to make the URLs easier to read and understand.

Domain name

Next is the domain name which consists of two parts. They are second level domain and top level domain.

Second Level Domain Name

The second level domain name refers to an organization or the name of a company. For example, the second level domain for the company called Little Lemon is littlelemon.

Top Level Domain

The part that follows the second level domain and concludes your domain name is called the top level domain.

It is used to reference a country or category of your organization. For example, a .com address can indicate a commercial entity, .org means an organization and .ie represents a country, sovereign state or dependent territory.

File Path

The file path also known as the page path directs you to the location of a resource. The resource may be any type of files that can be transmitted over HTTP, such as web documents, image files and metadata.

It’s worth remembering that a URL is simply an address where the files are stored. They can either be local or web based, which can be external to the domain.

When hosting locally, The resources such as images and web files are located on the user’s device or server.

When web based they exist on the user’s remote web server or external server.

Parameter

URL parameters are also known as query strings and are used to structure additional information inside a URL.

You use URL parameters to capture any part of the URL and pass its value for processing.

A query string is similar. It begins with a question mark symbol and is placed after the URL Path. It contains parameters represented as key value pairs that can appear inside a URL path. You can add more than one by adding the ampersand symbol between parameters.

Django can process both types of URL but mainly uses the URL parameters.

URL Design

URL design is the practice of purposefully creating URLs. So it’s important for Django developers to understand the different parts that make up A URL. This helps define well designed URLS, as the website content requirements determines how the URL will be constructed.


Parameters

In this reading, you’ll explore the different options for using parameters in a web application and showcase how they are related to the GET, PUT, POST and DELETE operations.

You’ll familiarize yourself with the differences between path, query, and body params and how they’re associated with HTTP methods such as GET, PUT, POST and DELETE.

The view function in Django is like any other Python function in that it receives its mandatory argument as the request object from the server context. The client may pass additional arguments via different methods. 

Path parameter

The client browser sends data along with the URL itself. For example, a URL such as http://example.com/customer/5. Here, the URL endpoint id, /customer/5, is the variable parameter (this can be any other number).

The parameter linked to the URL’s endpoint is called a path parameter. Note that there may be multiple path parameters in the URL, separated by / symbol.

For now, consider that the browser will use the URL http://localhost:8000/getuser/John/1

The URL dispatcher should identify John as the name parameter and 1 as the id parameter.

This pattern is mapped to the pathview() function with the following path in the URL patterns list in the app’s url.py file.

path('getuser/<name>/<id>', views.pathview, name='pathview'),

Next, add the pathview() function in views.py file.

from django.http import HttpResponse 
def pathview(request, name, id): 
    return HttpResponse("Name:{} UserID:{}".format(name, id)) 

As a result, the parameters in the above URL are parsed as name and id parameters and picked by the pathview() function, returning the displayed response.

An important thing to understand here is the parameters added inside the path() function in the urls.py file must match the arguments added inside the pathview() view function associated with it in the views.py file.

Path converters

The URL pattern treats the identifiers in angular brackets (<..>) as the path parameters. By default, it parses the received value to the string type. Other path converters available are:

  • str - Matches any non-empty string and excludes the path separator, ’/‘. This is the default if a converter isn’t included in the expression.
  • int - Matches zero or any positive integer and returns an int. For example:/customer/<int:id>
  • slug - Matches any slug string consisting of ASCII letters or numbers, including the hyphen and underscore characters.
  • uuid - Matches a formatted UUID.  For example: 075194d3-6885-417e-a8a8-6c931e272f00 and returns a UUID instance.
  • path - Matches any non-empty string and includes the path separator, ‘/’. 

Query parameter

The client URL may contain a query string linked to the endpoint, for example, http://localhost:8000/getuser/?name=John&id=1

A query string is a sequence of one or more key=value pairs concatenated by the & symbol. Each key is the query parameter. The query string ends with the ? symbol after the URL endpoint.

Query strings are an alternative approach to URL parameters for adding URL configurations.

The URL dispatcher doesn’t parse these parameters. They are fetched by the view from the request object it receives. The request object’s GET property is a dictionary object.

The key-value pairs in the query string are added to the request.GET property. Hence, the name can be obtained with request.GET[‘name’] expression.

The next step is to add the following path in the urls.py file:

path('getuser/', views.qryview, name='qryview')

Declare the qryview function in the views.py file.

def qryview(request): 
    name = request.GET['name'] 
    id = request.GET['id'] 
    return HttpResponse("Name:{} UserID:{}".format(name, id)) 

Now, start the server and use http://localhost:8000/myapp/?name=John&id=1

as the URL. The client gets back the response shown above.

Body parameters

An HTML form sends the data to the URL mentioned in its action attribute using the POST method. The POST method is a more secure way of sending data than the GET method because the data is not revealed in the URL. 

Let’s construct a simple form containing two text input elements. Then, save it as form.html in the templates folder.

<form action="/myapp/getform/" method="POST"> 
    {% csrf_token %} 
    <p>Name: <input type="text" name="id"></p> 
    <p>UserID :<input type="name" name="name"></p> 
    <input type="submit"> 
</form> 

The {% csrf_token %} tag is necessary to prevent cross-site forgery attacks. You’ll learn more about this later on in the course.

Next, you’ll need to provide a view that will render this form:

def showform(request): 
    return render(request, "form.html") 

The URL patterns list must be updated using the following path:

path("showform/", views.showform, name="showform"), 

The http://localhost:8000/myapp/showform/ URL displays this form to the user:

When this is submitted, it goes to the http://localhost:8000/myapp/getform/ URL. Now, map it to getform() function in the urls.py file.

path("getform/", views.getform, name='getform'),

The form data that the user posts becomes part of the request body.

Therefore, the name attribute of each form element becomes a body parameter and the data entered becomes its value.

The view function passes these body parameters from the request.POST dictionary-like attribute.

def getform(request): 
    if request.method == "POST": 
        id=request.POST['id'] 
        name=request.POST['name'] 
    return HttpResponse("Name:{} UserID:{}".format(name, id)) 

Complete the form and submit it. The getform() function returns the data as its response.

In the real world, the received data may be meaningfully processed, such as storing it in a database table.

You’ll learn how to do this when you explore Models, Forms and Database Connections.

In this reading, you learned about the path, query and body parameters and how to pass and process them using different HTTP methods.


Mapping URLs with Params

Sometimes developers need to pass information to the view function for additional processing. In Django, developers have the option to pass values as URL parameters by using URLs as source of information.

In Django, you can capture a value from a URL using angle brackets inside the path function where you define the URL.

urlpatterns = [
	path('drinks/<str:name>', views.drinks, name="drinks")
]

Captured values can optionally include something known as a converter type. For now, just know that to capture a string you can use the keyword STR followed by name for the value.

Then inside the views.py file you pass this name as an argument after the request object.

def drinks(request, name):
	query = name 
	return HttpResponse("<h1> %s </h1>" %query)

Example:

# view.py
 
from django.shortcuts import render
from django.http import HttpResponse
 
# Create your views here.
 
 
def menuitems(request, dish):
    items = {
        'pasta': 'Pasta masta dayee',
        'falafel': 'Felafele dayee! nagoozi!',
        'cheesecake': 'chiz cake dayee',
    }
 
    description = items[dish]
 
    return HttpResponse(f"<h2> {dish} </h2>" + description)
# urls.py (app level)
 
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('dishes/<str:dish>', views.menuitems),
]
# urls.py (project level)
 
"""
URL configuration for myproject project.
 
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp', include('myapp.urls')),
]
 

Developers can also use URL parameters to send information to the logic layer for processing or as search and sorting criteria.

Similarly, URL parameters can be used to fetch data that can be used with forms, data models, and other data structures.

Mapping URLs with parameters is also useful to create meaningful grouping of the content.


Additional resources

Click the links below to learn more about developing in Django.

Creating views– official documentation

Class-based views – Official

The render() function in Django

Getting query parameters from a request in Django

The HTTP server responses


PythonDjangoURLHTTP

Previous one → 5.Views | Next one → 7.Creating URLs and Views