Implementation:MarketSquare Robotframework browser New Context For API
New Context For API
API documentation for configuring New Context and New Browser for API testing scenarios.
Overview
The New Context keyword (defined in Browser/keywords/playwright_state.py) creates a new Playwright BrowserContext. While the keyword supports a wide range of parameters for UI testing (viewport, device emulation, etc.), this page documents the subset of parameters specifically relevant to API testing workflows where the context acts as an HTTP client environment.
Source Location
| Component | File | Lines |
|---|---|---|
new_context keyword |
Browser/keywords/playwright_state.py |
L576-692 |
new_browser keyword |
Browser/keywords/playwright_state.py |
L402-487 |
Keyword Signature (API-Relevant Parameters)
The full new_context signature includes many UI-oriented parameters. The following are the parameters relevant to API testing:
@keyword(tags=("Setter", "BrowserControl"))
def new_context(
self,
*,
baseURL: str | None = None,
clientCertificates: list[ClientCertificate] | None = None,
extraHTTPHeaders: dict[str, str] | None = None,
httpCredentials: HttpCredentials | None = None,
ignoreHTTPSErrors: bool = False,
offline: bool = False,
proxy: Proxy | None = None,
storageState: str | None = None,
# ... additional UI-focused parameters omitted ...
) -> str:
Returns: A stable identifier string for the created context, usable with Switch Context.
Parameter Reference
| Parameter | Type | Default | Description |
|---|---|---|---|
baseURL |
None | None |
Base URL used for resolving relative URLs in HTTP, Go To, Wait For Request, Wait For Response, and Wait For Navigation. Uses the JavaScript URL() constructor for resolution. Example: baseURL=http://localhost:3000 allows calling HTTP /api/users instead of the full URL.
|
extraHTTPHeaders |
None | None |
Dictionary of additional HTTP headers sent with every request from this context. All header values must be strings. Example: {'Authorization': 'Bearer token123', 'X-Custom': 'value'}.
|
httpCredentials |
None | None |
Credentials for HTTP Basic Authentication. The HttpCredentials TypedDict supports keys username, password, and optionally origin (to restrict credential sending to a specific scheme://host:port). Values are resolved internally and do not appear in Robot Framework logs.
|
ignoreHTTPSErrors |
bool |
False |
When True, HTTPS certificate errors during navigation and HTTP requests are suppressed. Required when testing against services with self-signed or invalid certificates.
|
clientCertificates |
None | None |
Client certificates for mTLS authentication. Each entry is a dictionary with origin (exact, no path), pfxPath or PEM-based paths, and optionally passphrase. The origin must be exact without any path component.
|
proxy |
None | None |
Network proxy settings. Structure: {'server': 'http://proxy:8080', 'bypass': '.example.com', 'username': 'user', 'password': 'pass'}. For Chromium on Windows, the browser itself must be launched with a global proxy for per-context proxy to work.
|
storageState |
None | None |
Path to a file created by Save Storage State containing cookies and local storage. Enables reusing authentication from a previous session.
|
offline |
bool |
False |
Toggles the context into offline mode. Useful for testing offline fallback behaviors in API scenarios. |
Usage Examples
Basic API context with baseURL and headers:
*** Settings ***
Library Browser
*** Test Cases ***
API Test With Base URL And Headers
New Browser chromium headless=True
${headers}= Create Dictionary Authorization=Bearer mytoken123 Accept=application/json
New Context baseURL=http://localhost:8080 extraHTTPHeaders=${headers} ignoreHTTPSErrors=True
New Page
&{resp}= HTTP /api/users method=GET
Should Be Equal As Integers ${resp.status} 200
API context with HTTP Basic Authentication:
*** Test Cases ***
API Test With Basic Auth
New Browser chromium headless=True
${creds}= Create Dictionary username=admin password=secret origin=http://localhost:8080
New Context baseURL=http://localhost:8080 httpCredentials=${creds}
New Page
&{resp}= HTTP /api/protected method=GET
Should Be Equal As Integers ${resp.status} 200
API context with client certificates (mTLS):
*** Test Cases ***
API Test With Client Certificate
New Browser chromium headless=True
${cert}= Create Dictionary origin=https://secure-api.example.com pfxPath=certificate.p12 passphrase=certpass
${certs}= Create List ${cert}
New Context baseURL=https://secure-api.example.com clientCertificates=${certs} ignoreHTTPSErrors=True
New Page
&{resp}= HTTP /api/secure-endpoint method=GET
Should Be Equal As Integers ${resp.status} 200
Internal Behavior
When New Context is called:
- Parameters are collected via
locals_to_params(locals()). httpCredentialsandstorageStatereceive special processing in_set_context_options(credentials are masked in logs).- Parameters are serialized to JSON and sent to the Node-side Playwright process via gRPC (
stub.NewBrowserorstub.NewContext). - The Node process calls Playwright's
browser.newContext(options). - A context ID is returned and cached for later reference.
If no browser is open when New Context is called, a new browser is automatically opened with default settings. The defaultBrowserType parameter can control which browser type is launched in this auto-open scenario.
Important Notes
- The
HTTPkeyword requires a page to exist in the context. Always callNew PageafterNew Context, even for purely API-focused tests, because the HTTP keyword executesfetch()within the page's JavaScript context. - The
extraHTTPHeadersapply to all requests from the context, including navigation and resource loading, not just explicitHTTPkeyword calls. - When
httpCredentialsincludes anorigin, credentials are only sent to matching servers. Withoutorigin, credentials are sent on any unauthorized (401) response.