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:
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.
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:
Although it is possible to render a hardcoded HTML string as the response, Django offers a better alternative to render a template web page.
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 responsecontent
: 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.
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.
Next, add the pathview()
function in views.py
file.
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 anint
. 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:
Declare the qryview
function in the views.py
file.
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.
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:
The URL patterns list must be updated using the following path:
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.
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.
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.
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.
Example:
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
Previous one â 5.Views | Next one â 7.Creating URLs and Views