How to Make a Web Server in Python

How to Make a Web Server in Python

On a daily basis, billions of people visit millions of websites, but have you ever wondered how websites open when you are typing a URL? Answer to that is a Web Server. And is it complicated to create your own web server?

Learning the mechanism of a HTTP server in Python is one of the most potent initial phases in becoming a master of backend development. You will not be writing some code that runs on your computer but you will be learning how to write programs to react to browser requests, serve web pages, and process routes, like real-life programs.

This blog will help you unveil everything. We will demonstrate how to make your server in Python, use the built-in Python HTTP server, and to serve the HTML files. By the end of this blog, you will not only know the theory but also have a local server running on your machine. Then you will be able to grow your learning to models such as Flask or Django and have the confidence to develop a full stack web application.

Students who transition to advanced programming concepts through real-world projects like web servers develop stronger problem-solving and logical thinking abilities.

Key Takeaways

  • This blog will teach you how to create a Python web server using simple, in-built tools.

  • The python http server enables first time users to have an easy time starting a local server without having to install cumbersome frameworks.

  • You will also learn how browsers interact with servers through HTTP requests and responses.

  • You’ll also understand how browsers communicate with servers using HTTP requests and responses.

  • Step-by-step examples will help you create the server Python projects that serve HTML files and handle custom routes.

  • And by the end of this blog you will not only know the theory, you will also have a local serving server.

Introduction to Web Servers

https connections and server command for full fledged web server

A Web server is a computer program that accepts requests made by a Web browser and provides web content such as HTML pages, images or data. Whenever you enter a URL into your browser or you click a link or even fill a form, your browser makes an HTTP request to a server. The server side of the system takes in the request and returns a response, which is typically an HTML page. This is a basic request and response cycle that the whole internet runs on.

The browser is simply the client and the web server is simply the responder in simple terms. Something is requested by the browser and it is provided by the server. Behind each web site, be it a small personal blog, or a big e-commerce site, is a web server that is processing thousands or millions of requests of this nature.

Understanding Web Server Basics

Web servers are an important concept to understand since we use these servers in our everyday sites and web applications. In the absence of servers, the world would have no system to accept requests, process information and render content. When developing the backend, interacting with servers is a fundamental task - one is responsible to perform business logic, access databases, handle authentication, and create APIs on servers.

Understanding of a HTTP server assists in clarification and practicality. You no longer perceive the internet as something abstract but you can see the logical flow of communication between a browser and a server. With having your own local server, you directly feel the influence of how the HTTP requests are processed, how the response is generated and how the content can be provided. This practical activity converts theory to practical knowledge.

On a lower level, a web server operates on the client-server model. The client (who is normally a web browser) makes the request requesting a particular resource and the server waits to receive the request and respond with the relevant data. The communication uses the HTTP protocol which provides the structure of messages sent and received as well as their interpretation by both parties.

Servers do work by listening on a particular port which you may consider as a communication doorway. IP address is used to identify the machine in a network whereas the port is used to identify a specific service which is running in the machine. E.g. When you launch a python server it may listen on localhost (your own computer) to port 8000. Your system is the only one that has access to it in this instance.

A server can equally be configured to bind to other network interfaces. When it is bound to the localhost only, it is only available locally. In case it sticks to your local network IP address, it can be accessed by other devices that use either the same Wi-Fi or LAN network with the same IP. This can come in handy particularly when the project has to be demonstrated, internally tested, or on a joint activity when you do not wish to expose your work to the rest of the internet.

What is a Web server?

A web-server is a software that allows the interaction of a browser with a Web site. In simple terms, it:

  • Waits for HTTP requests from clients (such as web browsers)

  • Processes those requests based on predefined logic

  • Sends back a response, usually in the form of HTML, images, or data

Every time you go to a Web site, your browser is the client and it sends out a request to a server requesting it to send particular content. The role of the server is just to listen and get to know what is being requested and respond with the relevant resource.

How Web servers work

Servers operate through a request-response cycle: browsers send HTTP requests to specific ports, servers process these requests based on URL paths and methods, then return appropriate content like HTML pages or error messages to complete the communication loop. A HTTP server is software that receives HTTP requests from browsers and sends back web content like HTML pages, images, or data forming the foundation of all web communication where browsers request resources and servers provide them. The servers have a well-organized cycle of operation called the request-response cycle:

  1. Browser sends a request – Once you have typed a URL or clicked on a link, your browser sends an HTTP request to the server.

  2. Server receives the request – The server is on a certain port, and it listens to any connection.

  3. Server processes the request – It specifies what resource is being requested, like a webpage or a database record.

  4. Server sends a response – The contents requested are sent back to the browser, which displays the same to the user.

This communication takes place through HTTP (Hypertext Transfer Protocol), which sets the format of messages and the way they are sent between clients and servers.

Role of web servers in website functionality

Web servers are the backbone of modern websites and applications. They:

  • Deliver web pages to users

  • Handle forms and process user input

  • Connect to databases to retrieve or store information

  • Manage APIs that allow different systems to communicate

Servers are the backbone of complete web applications and not just servers of static pages. They allow dynamic content, which means pages can be altered as a result of user intervention, data stored, or on-demand real-time updates. They also use access control as a measure to make sure that certain resources or sensitive data are accessed by the authorized users.

Setting Up Python for Web Servers

python program to build local network and address security concerns with source code

Python is an advanced programming language that is used to develop web servers because of its simplicity and readability. It is not too complicated to learn its syntax and understand how server logic is served, but it is also robust enough to be considered by professional applications. As it has in-built modules such as the http.server, one can initialize a basic server with a few lines of code.

Python has in-built tools that enable you to develop web server Python projects within seconds without having to install complicated software. The Python interpreter is used to run the scripts that compile and start your server, and it is simple to serve out web content in a few minutes. This ease is among the factors that make Python so easy to use for beginners and even experts in web development.

Required Python Modules

To build a basic application, Python provides several useful modules:

  • http.server (built-in) – A high-level module that allows you to quickly create a simple HTTP server for serving files and handling requests.

  • socket – A lower-level networking module that enables direct communication between machines over a network.

  • BaseHTTPRequestHandler – A class used to define how the server should handle incoming HTTP requests, such as GET or POST requests.

To have more control over how connections are handled, you might consider a Python socket server design. This operates on a lower level than that of http.server and provides you with more information about the way that network communication occurs at the low level.

Importing Necessary Libraries

You must import the modules that are needed in your script before a server is started. In a minimal configuration, this normally involves the importation of socketserver and the importation of http.server.

Suppose you would start your file by importing the HTTP server module and the socket server utility. The tools required to create, configure, and run the server are available in these imports to your script. This framework gives your program the knowledge of how to process the HTTP requests and network communication.

Setting Up Port and Handler

A port is a figure (such as 8000) that instructs your computer where it can accept the network traffic. The port number helps in identifying the port on which the server listens to any incoming connection. The importance of ports is that various applications have different numbers to eliminate conflicts. As an example, servers such as production typically use port 80 (HTTP) or 443 (HTTPS), whereas to test these on the local machine, programmers typically use a higher port, like 8000 or 8080.

When you start a Python server, it listens to a local address, 127.0.0.1 (localhost) by default (when you want the server to be seen only by your computer) or 0.0.0.0 (when you want the server to be seen by other devices on the same network). The binding links the server to a particular IP address and port where the operating system knows where to send incoming requests.

After the server is listening on a port, it can be said that it is prepared to receive the client request, such as the web browsers.

This is where handlers are involved. The special code pieces that determine the way the server handles inbound requests are known as handlers. They decide what is going to be returned to a person visiting a particular URL, whether the server is supposed to deliver an HTML page, handle a form submission, or provide back some data. The logic within your server response is in the handler, in simple terms.

You have the knowledge of ports, binding, and request handlers and form a solid base of Python web development as you progress beyond the stages of simply running scripts and start building systems that communicate on the web.

Writing Basic Server Code

In Python it is possible to write a simple HTTP server in a few lines. This will rely on Python code to create an easy HTTP server to use during development locally, which can be used to serve files in the given directory.

  • Defining a handler: Use Python's built-in http.server module to define a handler that manages HTTP requests.

  • Setting server address: Specify the address and port where the server will listen for incoming connections.

  • Starting the server: Use Python code to start the server, allowing it to begin serving files to clients.

Here’s a minimal example:

import http.server
import socketserver

Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", 8000), Handler) as httpd: print("serving at port", 8000) httpd.serve_forever()

  • The initial line loads required modules.

  • The "Handler" will be used to handle HTTP requests.

  • The server address is set to listen on all interfaces at port 8000.

  • The remaining two lines initiate the server and leave it running in order to be able to serve files in the present directory.

To start the server from your terminal, run the following command:

python -m http.server 8000

The above command will start a basic HTTP server, and when the server has been started, it will have the capacity to serve files to any client that will be connected to it. This is particularly handy when it comes to local development, testing, and file sharing.

Running Your First Web Server

You will need to open your terminal or command prompt to run your first server. Go to the folder where your Python server script is located. In Windows, it is possible to open Command Prompt in that folder. On Mac or Linux, open Terminal and change the directory with the command "cd".

Open your terminal or command prompt

Change the directory to the one you have a server script in. Create a command prompt (on Windows) or terminal (on Mac/Linux) in this directory. Your Python script will be run using the command line.

Start the server and access it

Execute your Python script with the command line. The default port that the built-in HTTP server uses is port 8000 (the default port), and the default directory is the current one unless you specify a different one. Such an arrangement establishes a local development and testing web server.

In order to connect to your server, turn on your browser and type the URL (such as http://localhost:8000) in the address bar.

Executing the Server Script

Once you’re inside the correct folder, run your script using a command like:

python filename.py

Once it has been run, you will usually see a message saying that the server is up and is listening on a given port (port 8000). It indicates that your server has started and it is now awaiting any requests.

Python has a default built-in HTTP server that runs on port 8000, which is used to serve files in the present directory unless you declare otherwise. You have now built a local development server.

Accessing the Server Through a Web Browser

Now open your web browser and type:

http://localhost:8000

into the address bar.

Provided all the settings are appropriate, you should see the default response, either a directory listing or the configured HTML file. This is evidence that your Python-based web server is operational and is able to respond to the requests of a browser.

Troubleshooting Common Setup Issues

It’s normal to encounter small issues when starting out. Here are common problems and solutions:

  • Port already in use: Another application may be using port 8000. Try stopping that program or run your server on a different port (like 8080).

  • Firewall blocking connection: Your system firewall may block access. Allow Python through the firewall settings.

  • Module not found error: Ensure Python is properly installed and that you’re using the correct version in your command line.

When a problem arises in your server when responding to a request, it could send an HTTP error such as 404 Not Found (page doesn’t exist) or 500 Internal Server Error (server-side problem). They are normal responses of HTTP communication and only point to an error that occurred.

Remember: errors are part of learning. Every developer encounters them, and each one helps you better understand how servers and web applications work.

Serving HTML Files

Now that your server is running, it’s time to move beyond plain text responses and start serving actual web pages.

Create an HTML file

First, create a simple HTML file that you want your server to serve. For example, save the following content as index.html in your working directory:

<!DOCTYPE html>
<html>
<head>
<title>My Python Web Server</title>
</head>
<body>
<h1>Hello from your Python web server!</h1>
</body>
</html>

Serve local files with Python's http.server

The inbuilt module in python called the http.server enables you to serve local files in a given directory. By a client requesting a file, the server finds the requested file on the directory structure and sends it back using the relevant headers. The default is to make files of the current directory available on the server, although you can specify another directory.

To start the server, run:

python -m http.server

This command will serve files from the current directory. If you want to serve files from another specified directory, use:

python -m http.server --directory /path/to/your/directory

It is better to understand your directory structure, as it defines which files can be accessed. In case a client makes a request to a directory that does not have an index.html file, the server will automatically create a directory listing, which will list all files and subdirectories in the directory.

Security Warning: Beware of symbolic links in your directories. The server can also take symbolic links, and this can expose files that are not in the desired directory. You should always check your directory structure and symbolic links to prevent accidental file publicity.

Creating HTML Files

Originally, in order to start serving real web content, create a basic file within your working directory called index.html. This file will serve as a starting point for your server.

Inside index.html, add a basic HTML structure. A simple page includes:

  • A <!DOCTYPE html> declaration

  • An <html> tag

  • A <head> section with a <title>

  • A <body> section with headings (<h1>) or paragraphs (<p>)

You could do this by putting in a heading such as "My First Python Web Server" and a brief welcome message in the body. Save the file to the directory where your server script is executing.

Configuring Server to Serve Static Files

Among the benefits of the built-in Python module - http.server, it will automatically serve the files in the current directory. This is because you do not require any additional setup. Your index.html file should be accessible as long as it is located in the same folder as the one where the server is currently operating.

The default is that, visiting the address of the server, when it is running, at port 8000, the server will look for an index.html file and show it. In the event that there is no index file, it can still display the listing of the directory.

Demonstrating File Serving Capabilities

To see it in action:

Now practice editing the HTML file edit the heading or underline and save it. Then refresh the browser. You will immediately notice the revised material.

This basic procedure demonstrates the actual Python web development. You are not only running code, but you are also delivering live web pages, making changes to them, and seeing the additions reflected instantly in the browser.

Customizing Your Web Server

following command for handling multiple connections and build protocol version for error response and restrict access

When you have a basic server, it is time to start personalizing your server to act more like a real-world application. This is where your project is developed into a more powerful and flexible one as opposed to a simple one.

Creating a Custom Request Handler

To tailor the behavior of your Python-based HTTP server to suit the needs of various kinds of incoming HTTP traffic, you may subclass BaseHTTPRequestHandler of the http.server module to create your own request handler (sometimes also known as a custom handler or own request handler). The request processor will be the one to take the request and produce an HTTP response.

Different HTTP methods (including GET and POST requests) can be treated by an implementation of a custom request handler, overriding methods such as do_GET and do_POST. This enables you to serve both dynamic and non-dynamic content, submit form responses, and use custom server code.

You are allowed to access the incoming request HTTP headers in your custom handler and can assign response headers to control metadata sent to the client. Methods may also be overridden to make the response code and status code (200 OK or 404 Not Found) in the HTTP response custom.

The handler takes the incoming HTTP requests and creates the correct response, which allows web applications to be prototyped or a simple web framework to be created. Remark: Python web frameworks such as Flask and Django are based on these ideas to offer more web development functionality.

Creating Custom Request Handlers

When you are no longer serving static files, you can override the response to your requests by making your server a subclass of BaseHTTPRequestHandler. To put it simply, this is the creation of your own class, which extends to it and its definition of how particular requests are to be processed.

You can also take control of the action that a browser takes on a GET request by overriding functions such as do_GET. Within this approach, you are able to specify the status code of the response (200 to mean success), you can specify the headers and you can also send back custom content, which could be an HTML, plain text or a JSON file. This is the point at which you begin to influence the behaviour of your application, and not just act as a file server.

Implementing Routing

Routing enables the paths of various URLs to yield different contents. Your server can examine the requested path and make a decision of what to display rather than responding in the same manner to all requests.

For example:

  • Visiting /about could return an “About Us” page.

  • Visiting /contact could return contact information.

Simple mapping of URLs to responses is the basis of the operation of real web applications. Once you build Python projects on web servers with custom routing, you are one step further to the construction of structured applications as opposed to simple file servers.

Handling Different URL Paths

Conditional statements are normally used to manage routing logic. Within the request handler, you look at the path that has been requested and reply to it. As an example, the path /about should be followed in one instance, and the path /contact should be followed in another; otherwise, the 404 error should be returned.

These condition checks enable your server to dynamically determine the content to serve. Although the arrangement is basic, this is the same method modern structures use to handle the routes in the background so you have a real-world experience of what real backend logic entails.

Advanced Web Server Techniques

Once you’re comfortable with a basic server, you can explore more advanced concepts without diving into heavy frameworks.

To further control it, you are able to write a TCP server in Python using the socket module. A TCP server, unlike higher-level HTTP servers, operates on the basis of raw socket connections. This also assists you to know what is occurring behind each web request, as HTTP is over TCP.

In the case of HTTP, the server takes in the stream of bytes on TCP, and decodes it on the basis of the HTTP protocol. Every request begins with a request line such as GET /index.html HTTP/1.1, is followed by a set of headers, and then a blank line is followed by the body. Being aware of this structure will make you interpret requests and send answers appropriately.

Python scripts may be executed as CGI programs in order to generate dynamic content. CGI is an older technology but demonstrates how the servers run the code to accomplish a form process, user authentication and custom output. To provide a secure communication, you may provide the HTTPS with a TLS certificate and a key. The private key should be kept safe so as to guarantee encrypted data transfer.

Another way to enhance security is to tie your server to interfaces. Localhost means only your machine can be accessed and using a local IP means other computers on the network can also be accessed.

Adding More Complex Routing

You can create a mapping of various URLs to a given function as your project becomes larger. An example is that /home can serve a webpage whereas /api/data can serve a JSON. The basis of the Rest-style endpoints in actual applications is this.

Handling Different HTTP Methods

  • GET retrieves data (like loading a page).

  • POST sends data to the server (like submitting a form).

Forms use POST because it sends data in the request body rather than exposing it in the URL.

Basic Error Handling

When a page does not exist, a good server is expected to respond with 404 Not Found. The try-except blocks avoid crashes and enable the graceful handling of errors. Shut down mechanisms should also be used in a proper manner to close the server in a clean manner.

These methods are related directly to the real world Python HTTP server applications. Production-ready web systems also use the same fundamentals routing, methods, security, and error handling.

Conclusion

We hope that by now you must have constructed a server in Python. In this process, you got to know the basics of the request-response cycle, how browsers talk to servers in HTTP, how HTML files are served to show web pages, how routing can be customized to make your server handle various URLs in different ways. What was so complicated before becomes something that you have already put into practice.

You have now made a big step into the realms of backend systems and python web development. You have now learned the functionality of ports, the actions of handlers, and the delivery of content between server and browser some of the fundamental concepts that make up real-world applications.

Now you may go on to develop your skill set further by studying frameworks such as Flask or Django, or you can simply make a simple API to return some JSON data, connect your project to a database, or you can learn about full-stack development by integrating a frontend and a backend system.

Codeyoung has taught 50,000+ students, and delivered 3.5 million classes to students worldwide, giving it a profound understanding of what students should be taught about coding based on their age. This experience uncovers trends that are always indicative of student success particularly when the students transfer knowledge of concepts into the creation of actual and practical projects such as it is the case with this project.

Every modern web app started with a simple server and now you’ve built one.

FAQs: Python Script for Server Running

How to host a web server using Python?

All modern web applications began with a simple server. The python language has an inbuilt module called http.server that can be used to host a basic server. Once Python is installed, you can change directory to your project folder and type a simple command, such as

python -m http.server 8000

where you can start a local server on port 8000.

This enables you to use HTML files and other non-dynamic files as is on the same folder. To make more advanced hosting (e.g. public deployment) you would commonly use more frameworks like Flask or Django and production servers such as Gunicorn or uWSGI.

Is Python good for web servers?

Indeed, Python is generally regarded as a great language to use in web servers because of its clean syntax, readability and rich ecosystem. It can favor both the basic setups of the server to beginners and the huge setups of more complex production systems to the businesses.

Web frameworks such as flask and Django are so much easier to use to construct secure and scaleable web-based applications whereas python has a huge variety of libraries, which can enable easy integration of databases, developing API, and authentication among others.

How to make a HTTP server in Python?

In Python, a simple HTTP server can be built using the default http.server module which includes classes to process HTTP requests ready to use. Importing the module and providing a port number to start the server (say 8000) enables one to establish a server that would respond to incoming browser requests and contain files that are listed in the current directory. This is among the easiest ways of knowing how request-response communication in web development works.

What does Python HTTP server 8000 do?

A Python HTTP server is run on port 8000 and it enables a local web server that waits on the port 8000 until it receives an incoming HTTP request. Port 8000 provides a means of communication between your browser and the server.

When you open your browser and type in the location, localhost:8000, your system will connect with it on that port and list the files that are available to serve in your working directory. It is usually utilized to develop and test.

Can Python be used for web development?

Python is, by far, among the most popular web development languages. One can create simple and even data-driven web applications based on it. Python is also a good option to consider as both novices and advanced developers with frameworks such as Flask to build lightweight applications and Django to build full-fledged applications, which use routing, database connections, user authentication, API development, and dynamic content generation.

Turn your child’s curiosity into creativity 🚀

Book a free 1:1 trial class and see how Codeyoung makes learning fun and effective.

Codeyoung Perspectives

Codeyoung Perspectives is a thought space where educators, parents, and innovators explore ideas shaping how children learn in the digital age. From coding and creativity to strong foundational math, critical thinking and future skills, we share insights, stories, and expert opinions to inspire better learning experiences for every child.