Request and Response
Nexios Request Object
In Nexios, the req
object represents an incoming HTTP request and provides access to various request details such as the query parameters, URL parameters, request body, headers, and more. Similarly, the res
object is used to handle the HTTP response, allowing you to send data back to the client. By convention, these objects are typically referred to as req
and res
, but their actual names depend on the parameters specified in the route handler function.
For example, a basic route in Nexios might look like this:
However, you could use different parameter names if preferred:
In both cases, id
is extracted from the URL, demonstrating how Nexios allows flexibility in handling HTTP requests while maintaining readability and structure.
Properties
request.app
In Nexios, the request.app property provides a reference to the instance of the Nexios application that is utilizing the middleware.
If you follow a modular approach where a middleware function is defined in a separate module and then imported into your main application file, the middleware can access the Nexios instance through request.app.
request.base_url
In Nexios, the request.base_url
property returns the base URL of the incoming request, excluding any query parameters or additional path segments. This is useful when you need to construct absolute URLs or reference the root endpoint of a request.
For example:
request.json
The request.json
property retrieves the parsed JSON body from an incoming request. This is useful when handling API requests where the client sends JSON data.
request.form_data
The request.form_data property retrieves data from application/x-www-form-urlencoded form submissions. This is commonly used for HTML forms.
request.files
The request.files
property allows you to handle file uploads, extracting files sent through multipart/form-data
.
request.text
The request.text
property retrieves the raw text body from an incoming request. This is useful when handling plain text payloads, logs, or custom data formats that are not JSON or form-encoded.
request.method
The request.method
property returns the HTTP method used in the request (e.g., "GET", "POST", "PUT", "DELETE").
request.stream()
The request.stream()
method allows reading the request body as a stream, useful for large payloads like file uploads or big JSON objects.
request.build_absolute_uri
The request.build_absolute_uri()
method constructs an absolute URL based on the current request. This is useful when generating links for redirects, API responses, or email templates.
request.state
The request.state
property allows passing data between middlewares and route handlers, similar to request attributes in Express.js.
request.client
The request.client
property returns a tuple (host, port), representing the client’s IP address and port.
request.headers
The request.headers
property is a dictionary-like object that contains all incoming HTTP headers.
request.cookies
The request.cookies property allows retrieving cookies sent by the client.
Nexios Response Object
The Nexios Response object provides a fluent interface for building HTTP responses , similar to Express.js. It supports various response types, headers, cookies, caching, and redirections. All methods return the instance itself, enabling method chaining.
Methods
text(content, status_code=200, headers={})
Sends a plain text response.
Parameters:
content
: Text content to send (string or JSONType).status_code
: HTTP status code (default: 200).headers
: Custom headers (optional).
Example:
json(data, status_code=200, headers={}, indent=None, ensure_ascii=True)
Sends a JSON response.
Parameters:
data
: Data to serialize as JSON.status_code
: HTTP status code (default: 200).headers
: Custom headers (optional).indent
: JSON indentation (optional).ensure_ascii
: Escape non-ASCII characters (default: True).
Example:
html(content, status_code=200, headers={})
Sends an HTML response.
Parameters:
content
: HTML content to send.status_code
: HTTP status code (default: 200).headers
: Custom headers (optional).
Example:
file(path, filename=None, content_disposition_type="inline")
Sends a file as the response.
Parameters:
path
: Path to the file (string orPath
).filename
: Custom filename (optional).content_disposition_type
:"inline"
(display in browser) or"attachment"
(download).
Example:
stream(iterator, content_type="text/plain")
Streams content from an asynchronous iterator.
Parameters:
iterator
: Asynchronous generator yielding chunks.content_type
: MIME type of the stream (default:text/plain
).
Example:
redirect(url, status_code=302)
Redirects to a URL.
Parameters:
url
: Target URL.status_code
: Redirect status code (default: 302).
Example:
status(status_code)
Sets the HTTP status code.
Parameters:
status_code
: Status code (e.g., 200, 404).
Example:
header(key, value)
Adds a custom header.
Parameters:
key
: Header name (case-insensitive).value
: Header value.
Example:
set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=True, httponly=False, samesite="lax")
Sets a cookie.
Parameters:
key
: Cookie name.value
: Cookie value.max_age
: Max age in seconds (optional).expires
: Expiry datetime (optional).path
: Cookie path (default:/
).domain
: Domain scope (optional).secure
: HTTPS-only (default: True).httponly
: Prevent client-side JS access (default: False).samesite
:"lax"
,"strict"
, or"none"
(default:"lax"
).
Example:
delete_cookie(key, path="/", domain=None)
Deletes a cookie.
Parameters:
key
: Cookie name.path
: Cookie path (default:/
).domain
: Domain scope (optional).
Example:
cache(max_age=3600, private=True)
Enables caching with Cache-Control
headers.
Parameters:
max_age
: Cache duration in seconds (default: 3600).private
:private
(user-specific) orpublic
caching (default: True).
Example:
no_cache()
Disables caching.
Example:
**resp(body="", status_code=200, headers=None, content_type="text/plain")** Directly configures the underlying
Response` object.
Parameters:
body
: Raw response body.status_code
: HTTP status code.headers
: Custom headers (optional).content_type
: MIME type (default:text/plain
).
Example:
funny example