Introduction: What is HTTP and Why Do We Need It?
11. Introduction: What is HTTP and Why Do We Need It?
Welcome to Lesson 11! So far, you have learned Python basics, object-oriented programming, and how to manage packages. Now, we are ready to build something that communicates over the internet. But before we write any API code, we must understand the language that computers use to talk to each other: HTTP. This chapter explains what HTTP is, how it works, and why it is the foundation of every REST API.
What is HTTP?
HTTP stands for HyperText Transfer Protocol. It is a set of rules that allows a client (like your web browser or a mobile app) to request resources from a server (a remote computer that stores data). When you visit a website, your browser sends an HTTP request to the server, and the server sends back an HTTP response. This request-response cycle is the core of web communication.
Why Do We Need HTTP?
Without a common protocol, every application would need its own custom way to communicate. HTTP provides a standard, simple, and reliable method for exchanging data. It works over the internet, supports different types of data (HTML, JSON, images), and is understood by almost every programming language and platform. For a REST API, HTTP is the transport layer that carries your data between the client and your Python backend.
Key Components of an HTTP Request
Every HTTP request has four main parts:
- Method (Verb): Tells the server what action to perform. Common methods are GET (retrieve data), POST (create new data), PUT (update data), and DELETE (remove data).
- URL (Endpoint): The address of the resource you want to interact with, for example
https://api.example.com/tasks. - Headers: Extra information sent with the request, such as authentication tokens or the type of data you accept.
- Body (optional): Data sent to the server, usually in JSON format, used with POST and PUT requests.
Key Components of an HTTP Response
When the server processes your request, it sends back a response that includes:
- Status Code: A three-digit number that indicates the result. For example, 200 means success, 404 means not found, and 500 means server error.
- Headers: Metadata about the response, like the content type (e.g.,
application/json). - Body: The actual data returned by the server, often in JSON format.
What is REST?
REST stands for Representational State Transfer. It is an architectural style for designing networked applications. A REST API uses HTTP methods to perform CRUD operations (Create, Read, Update, Delete) on resources. Resources are usually represented as URLs, and data is exchanged in a lightweight format like JSON. The key principles of REST include:
- Statelessness: Each request from a client contains all the information needed to process it. The server does not store any client context between requests.
- Uniform Interface: Resources are identified by URLs, and actions are performed using standard HTTP methods.
- Client-Server Separation: The client and server evolve independently as long as the interface stays consistent.
Practical Example: Simulating an HTTP Request with Python
Even though we haven't installed FastAPI yet, we can use Python's built-in http.server module to see a simple HTTP exchange. Let's create a minimal server that responds to a GET request.
# simple_server.py
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'Hello from HTTP! This is a response.')
if __name__ == '__main__':
server = HTTPServer(('localhost', 8000), SimpleHandler)
print('Server running on http://localhost:8000')
server.serve_forever()
Step-by-step explanation:
- We import
HTTPServerandBaseHTTPRequestHandlerfrom Python's standard library. - We create a class
SimpleHandlerthat inherits fromBaseHTTPRequestHandler. - We override the
do_GETmethod to handle GET requests. Inside, we send a 200 status code, set the content type to plain text, and write a simple message as the response body. - We start the server on
localhost:8000and keep it running.
To test it, run the script and open your browser at http://localhost:8000. You will see the message "Hello from HTTP! This is a response." This is a real HTTP response!
Common Mistakes Beginners Make
- Confusing HTTP methods: Using GET to send data that should be sent with POST. GET requests should only retrieve data, not change server state.
- Ignoring status codes: Always check the status code in your API responses. A 200 does not always mean success if you expected a 201 (created).
- Forgetting headers: Headers like
Content-Typeare essential. If you send JSON but forget to set the header, the server may not parse it correctly.
Practice Task
Task: Modify the simple server above to handle a POST request. In the do_POST method, read the request body (use self.rfile.read(int(self.headers['Content-Length']))), print it to the console, and send back a 201 status code with the message "Data received".
Hint: You need to add a do_POST method similar to do_GET, but read the incoming data first.
Understanding HTTP and REST is the bridge between your Python knowledge and building real-world APIs. In the next lesson, we will install FastAPI and create our first endpoint. You are now ready to move from theory to practice!

Loading ratings...