HTTP Request Parser - Problem

Parse a raw HTTP request string into a structured object containing the request method, path, headers, query parameters, and body.

An HTTP request has the following format:

  • Request Line: METHOD /path?query HTTP/1.1
  • Headers: Header-Name: Header-Value (one per line)
  • Empty Line: Separates headers from body
  • Body: Optional request body content

Return an object with fields: method, path, query (as object), headers (as object), and body.

Input & Output

Example 1 — GET Request with Query Parameters
$ Input: GET /users?id=123&name=john HTTP/1.1\nHost: api.example.com\nContent-Type: application/json\n\n{"data": "test"}
Output: {"method":"GET","path":"/users","query":{"id":"123","name":"john"},"headers":{"Host":"api.example.com","Content-Type":"application/json"},"body":"{\"data\": \"test\"}"}
💡 Note: Parses GET request with query parameters id=123&name=john, extracts headers, and captures JSON body
Example 2 — POST Request without Query
$ Input: POST /api/users HTTP/1.1\nAuthorization: Bearer token123\n\n{"name":"Alice","age":25}
Output: {"method":"POST","path":"/api/users","query":{},"headers":{"Authorization":"Bearer token123"},"body":"{\"name\":\"Alice\",\"age\":25}"}
💡 Note: POST request to /api/users with Authorization header and JSON body containing user data
Example 3 — Simple GET without Body
$ Input: GET /health HTTP/1.1\nUser-Agent: Mozilla/5.0\n\n
Output: {"method":"GET","path":"/health","query":{},"headers":{"User-Agent":"Mozilla/5.0"},"body":""}
💡 Note: Simple health check request with no query parameters and empty body

Constraints

  • 1 ≤ rawRequest.length ≤ 104
  • HTTP method is one of: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
  • Path starts with '/' character
  • Headers follow 'Key: Value' format
  • Empty line separates headers from body

Visualization

Tap to expand
INPUTRaw HTTP RequestGET /users?id=123 HTTP/1.1Host: api.example.comContent-Type: application/json{"data": "test"}Unstructured text formatMixed content typesRequires careful parsingALGORITHMState Machine Parser1Parse Request LineExtract method, path, query2Process HeadersKey:Value pairs until empty line3Extract BodyContent after empty line4Build Result ObjectOrganize into JSON structureRESULTStructured Object{ "method": "GET", "path": "/users", "query": {"id": "123"}, "headers": { "Host": "api.example.com" }, "body": "{\"data\": \"test\"}"}"}Clean JSON structureReady for application useKey Insight:Understanding HTTP structure enables efficient single-pass parsing with state transitionsinstead of multiple scans and complex string operationsTutorialsPoint - HTTP Request Parser | State Machine Approach
Asked in
Google 42 Amazon 38 Microsoft 35 Netflix 28
76.5K Views
Medium-High Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen