H4.dart

Requests

Utilties to help access important information about incoming requests.

readBody

Parse incoming request body

Future<dynamic> readBody(H4Event event)

Parameters:

ParameterTypeDescription
eventH4EventRequest event object

Returns:

  • If the content type header is application/json: Parsed JSON data as a Map<String, dynamic> or List<dynamic> from dart:convert
  • Otherwise: Raw text body as a String

Example

index.dart
router.post("/data", (event) async {
  final body = await readBody(event); 
  // body is a Map<String, dynamic>
  // or List<dynamic> if JSON array
  // e.g. [1, 2, 3] or {"a": 1, "b": 2}
  return {'data': body};
});

Read source


getQueryParam

Retrieve a query parameter value from the request

String? getQueryParam(
  H4Event event,
  String paramName, {
  bool decode = true
})

Parameters:

ParameterTypeDefaultDescription
eventH4Event-The request event object
paramNameString-Name of query parameter to get
decodebooltrueURL-decode the parameter value

Returns:
The parameter value as String or null if not found

Example

example.dart
router.get("/search", (event) {
  final query = getQueryParam(event, 'q');
  return {'results': searchDatabase(query)};
});

getHeader

Get a request header value

String? getHeader(
  H4Event event,
  String headerName
)

Parameters:

ParameterTypeDescription
eventH4EventRequest event object
headerNameStringCase-insensitive header name

Returns:
Header value or null if not present

Example:

example.dart
router.get("/auth", (event) {
  final token = getHeader(event, 'authorization');
  return authenticateUser(token);
});

getRouteParam

Extract path parameter from route

String? getRouteParam(
  H4Event event,
  String paramName
)

Parameters:

ParameterTypeDescription
eventH4EventRequest event object
paramNameStringPath parameter name to extract

Example:

example.dart
router.get("/users/:id", (event) {
  final userId = getRouteParam(event, 'id');
  return fetchUser(userId);
});

getRequestCookies

Parse cookies from request headers

Map<String, String> getRequestCookies(H4Event event)

Returns:
Map of cookie names to values

Example:

example.dart
router.get("/prefs", (event) {
  final cookies = getRequestCookies(event);
  return getUserPreferences(cookies['sessionId']);
});

readFiles

Process multipart file uploads from request

Future<List<UploadedFile>> readFiles(H4Event event)

Parameters:

ParameterTypeDescription
eventH4EventRequest event object

Returns:
List of UploadedFile instances

Behavior:

  • Parses multipart/form-data requests
  • Extracts all file upload parts
  • Reads file contents into memory
  • Returns structured file metadata and content

Example:

index.dart
// Existing code..
 
router.post("/upload", (event) async {
  final files = await readFiles(event);
  final file = files.first;
 
  return {
    'filename': file.filename,
    'size': file.size,
    'type': file.contentType
  };
});

On this page