Created
May 13, 2025 13:15
-
-
Save deepanshumehtaa/7fed9629633ba8d0df799f3cea27faf0 to your computer and use it in GitHub Desktop.
python socket server - post api.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import socket | |
def parse_http_request(request): | |
headers, _, body = request.partition("\r\n\r\n") | |
request_line = headers.splitlines()[0] | |
method, path, _ = request_line.split() | |
return method, path, headers, body | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.bind(('localhost', 9201)) | |
server.listen(1) | |
print("Server listening on http://localhost:9200") | |
while True: | |
conn, addr = server.accept() | |
print(f"Connection from {addr}") | |
request = conn.recv(4096).decode() | |
if not request: | |
print("close conn...") | |
conn.close() | |
continue | |
method, path, headers, body = parse_http_request(request) | |
if method == 'POST' and path == '/post': | |
try: | |
json_data = json.loads(body) | |
print(f"Received JSON: {json_data}") | |
response_body = json.dumps({ | |
"message": "Hello from Python!", | |
"status": "success" | |
}) | |
response = ( | |
"HTTP/1.1 200 OK\r\n" | |
"Content-Type: application/json\r\n" | |
f"Content-Length: {len(response_body)}\r\n" | |
"Connection: close\r\n" | |
"\r\n" | |
f"{response_body}" | |
) | |
except json.JSONDecodeError: | |
response = ( | |
"HTTP/1.1 400 Bad Request\r\n" | |
"Content-Type: text/plain\r\n" | |
"Connection: close\r\n" | |
"\r\n" | |
"Invalid JSON" | |
) | |
else: | |
response_body = json.dumps({ | |
"message": "path not found", | |
"status": "fail" | |
}) | |
response = ( | |
"HTTP/1.1 404 Not Found\r\n" | |
"Content-Type: text/plain\r\n" | |
"Connection: close\r\n" | |
"\r\n" | |
f"{response_body}" | |
) | |
conn.sendall(response.encode()) | |
print("close conn...") | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment