### Install Niquests with HTTP/3 support Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with HTTP/3 support, which forces the installation of the qh3 dependency. ```bash $ python -m pip install niquests[http3] ``` -------------------------------- ### Example Usage with Patched Requests-Mock Source: https://github.com/jawah/niquests/blob/main/docs/community/extensions.md Demonstrates how to use the patched requests-mock fixture to mock a GET request. ```python def test_sometime(patched_requests_mock): patched_requests_mock.get("https://example.com/", text="hello world") ``` -------------------------------- ### Install Niquests with full extras Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with all available optional features, excluding utls. ```bash $ python -m pip install niquests[full] ``` -------------------------------- ### Install Niquests with WebSocket support Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with the integrated WebSocket experience enabled. ```bash $ python -m pip install niquests[ws] ``` -------------------------------- ### Running Niquests in Pyodide (Synchronous) Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md This example demonstrates a basic HTTP GET request using niquests that works identically in both CPython and Pyodide environments. ```python # This exact code works in both CPython and Pyodide: import niquests resp = niquests.get("https://httpbingo.org/get") print(resp.json()) ``` -------------------------------- ### Running Niquests in Pyodide (Asynchronous) Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md This example demonstrates a basic asynchronous HTTP GET request using niquests that works identically in both CPython and Pyodide environments. ```python # This exact code works in both CPython and Pyodide: import niquests resp = await niquests.aget("https://httpbingo.org/get") print(resp.json()) ``` -------------------------------- ### Supported DNS URL Examples Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Examples of various supported DNS URL formats for different protocols and providers. ```default "doh+google://" # shortcut url for Google DNS over HTTPS "dot+google://" # shortcut url for Google DNS over TLS "doh+cloudflare://" # shortcut url for Cloudflare DNS over HTTPS "doq+adguard://" # shortcut url for Adguard DNS over QUIC "dou://1.1.1.1" # url for DNS over UDP (Plain resolver) "dou://1.1.1.1:8853" # url for DNS over UDP using port 8853 (Plain resolver) "doh://my-resolver.tld" # url for DNS over HTTPS using server my-resolver.tld ``` -------------------------------- ### Install Niquests with UTLS support Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Install Niquests with the `utls` extra to enable swappable TLS backends for browser impersonation. ```default pip install niquests[utls] ``` -------------------------------- ### Install Niquests with multiple extras Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with a combination of optional extras, such as SOCKS and WebSocket support. ```bash $ python -m pip install niquests[socks,ws] ``` -------------------------------- ### Install niquests-mock Source: https://github.com/jawah/niquests/blob/main/docs/community/extensions.md Install the niquests-mock library using pip. This library provides HTTP mocking capabilities for Niquests. ```bash pip install niquests-mock ``` -------------------------------- ### Install Niquests Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install the core Niquests package using pip. ```bash $ python -m pip install niquests ``` -------------------------------- ### Install opentelemetry-instrumentation-niquests Source: https://github.com/jawah/niquests/blob/main/docs/community/extensions.md Install the OpenTelemetry instrumentation package for Niquests using pip. ```bash pip install opentelemetry-instrumentation-niquests ``` -------------------------------- ### Install Niquests with SOCKS proxy support Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests to enable SOCKS proxy functionality. ```bash $ python -m pip install niquests[socks] ``` -------------------------------- ### Install Niquests with Zstandard only Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with only the Zstandard decompression support, excluding orjson. ```bash $ python -m pip install niquests[zstd] ``` -------------------------------- ### Basic Async Function Structure Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md This snippet shows the required structure for running any asynchronous Niquests example. Ensure Niquests is installed and up-to-date before use. ```python import asyncio import niquests async def main() -> None: """paste your example code here!""" if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Enable HTTP/3 Support Source: https://github.com/jawah/niquests/blob/main/HISTORY.md Force install HTTP/3 support in your environment if not present. This is an extra-dist install option. ```python pip install niquests[http3] ``` -------------------------------- ### Install Niquests Locally Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Navigate to the Niquests source directory and install it into your Python environment using pip. ```bash $ cd niquests $ python -m pip install . ``` -------------------------------- ### Install Niquests with speedups (Brotli, Zstandard, orjson) Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests with performance enhancements including Brotli and Zstandard decompression, and the orjson decoder. ```bash $ python -m pip install niquests[speedups] ``` -------------------------------- ### Install Niquests Source: https://github.com/jawah/niquests/blob/main/README.md Install Niquests using pip. This command is used to add the library to your Python environment. ```console python -m pip install niquests ``` -------------------------------- ### Making a GET Request Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Initiates a GET request to a specified URL and returns a Response object. ```default >>> r = niquests.get('https://en.wikipedia.org/wiki/Monty_Python') ``` -------------------------------- ### Install Niquests with Rustls backend Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests to use the Rustls backend for TLS instead of OpenSSL/LibreSSL. ```bash $ python -m pip install niquests[rtls] ``` -------------------------------- ### Install niquests-cache Source: https://github.com/jawah/niquests/blob/main/docs/community/extensions.md Install the niquests-cache library using pip. This library adds HTTP response caching to Niquests. ```bash pip install niquests-cache ``` -------------------------------- ### Install Niquests with BoringSSL backend Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests to use the BoringSSL backend for TLS, similar to Google Chrome. ```bash $ python -m pip install niquests[utls] ``` -------------------------------- ### Running requests.help command Source: https://github.com/jawah/niquests/blob/main/docs/community/updates.md Shows how to execute the 'requests.help' command from the command line for debugging purposes. This command includes information about the installed version of idna. ```bash $ python -m requests.help ``` -------------------------------- ### Enable Certificate Revocation Support Source: https://github.com/jawah/niquests/blob/main/HISTORY.md Force install certificate revocation support in your environment if not present. This is an extra-dist install option. ```python pip install niquests[ocsp] ``` -------------------------------- ### Preparing a GET Request with Session State (Synchronous) Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Prepares a GET request using Session.prepare_request to include session-level state like cookies before modification and sending. This preserves session advantages. ```python from niquests import Request, Session s = Session() req = Request('GET', url, data=data, headers=headers) prepped = s.prepare_request(req) # do something with prepped.body prepped.body = 'Seriously, send exactly these bytes.' # do something with prepped.headers prepped.headers['Keep-Dead'] = 'parrot' resp = s.send(prepped, stream=stream, verify=verify, proxies=proxies, cert=cert, timeout=timeout ) print(resp.status_code) ``` -------------------------------- ### Install Requests with chardet support on Python 3 Source: https://github.com/jawah/niquests/blob/main/HISTORY.md To install Requests and explicitly use the chardet package for Python 3 compatibility, use the specified extra. ```shell pip install "requests[use_chardet_on_py3]" ``` -------------------------------- ### Basic Niquests Session and GET Request Source: https://github.com/jawah/niquests/blob/main/docs/index.md Demonstrates creating a Niquests Session with DNS over HTTPS and making a GET request with basic authentication. Shows how to access response status code, headers, encoding, text, JSON content, and connection information. ```python >>> import niquests >>> s = niquests.Session(resolver="doh+google://") >>> r = s.get('https://pie.dev/basic-auth/user/pass', auth=('user', 'pass')) >>> r.status_code 200 >>> r.headers['content-type'] 'application/json; charset=utf-8' >>> r.oheaders.content_type.charset 'utf-8' >>> r.encoding 'utf-8' >>> r.text '{"authenticated": true, ...}' >>> r.json() {'authenticated': True, ...} >>> r >>> r.ocsp_verified True >>> r.conn_info.established_latency datetime.timedelta(microseconds=38) ``` -------------------------------- ### Install Niquests with Rustls Backend Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Install Niquests with the Rustls backend for a memory-safe TLS implementation. This is a drop-in replacement for the standard SSL module. ```default pip install niquests[rtls] ``` -------------------------------- ### Preparing a GET Request with Session State (Asynchronous) Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Prepares a GET request using AsyncSession.prepare_request to include session-level state like cookies before modification. This preserves session advantages in async operations. ```python from niquests import Request, AsyncSession s = AsyncSession() req = Request('GET', url, data=data, headers=headers) prepped = s.prepare_request(req) # do something with prepped.body prepped.body = 'Seriously, send exactly these bytes.' # do something with prepped.headers prepped.headers['Keep-Dead'] = 'parrot' resp = await s.send(prepped, stream=stream, verify=verify, proxies=proxies, cert=cert, timeout=timeout ) ``` -------------------------------- ### Asynchronous GET Request Source: https://github.com/jawah/niquests/blob/main/README.md Demonstrates how to perform an asynchronous GET request using niquests with async/await syntax. Shows handling of streaming responses and standard responses. ```APIDOC ## Asynchronous GET Request ### Description Performs an asynchronous GET request using `niquests.aget`. Handles both streaming and non-streaming responses. ### Method `await niquests.aget(url, stream=False, **kwargs)` ### Endpoint `https://one.one.one.one` ### Parameters - **url** (string) - Required - The URL to send the GET request to. - **stream** (bool) - Optional - If True, the response is streamed. - **kwargs** - Optional - Additional keyword arguments for the request. ### Request Example ```python import niquests import asyncio async def main() -> None: # With stream=True r_stream = await niquests.aget('https://one.one.one.one', stream=True) print(r_stream) payload_stream = await r_stream.text print(payload_stream) # Without stream=True r_no_stream = await niquests.aget('https://one.one.one.one') print(r_no_stream) payload_no_stream = r_no_stream.text print(payload_no_stream) asyncio.run(main()) ``` ### Response #### Success Response (200) - **Response Object** - The response object from the asynchronous request. - **text** (str) - The response body as a string. For streaming responses, this needs to be awaited. ``` -------------------------------- ### Creating an Image from Binary Content Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Example of creating an image from binary data returned by a request using Pillow and BytesIO. ```python >>> from PIL import Image >>> from io import BytesIO >>> i = Image.open(BytesIO(r.content)) ``` -------------------------------- ### Other Synchronous HTTP Methods Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates making PUT, DELETE, HEAD, and OPTIONS requests synchronously. These methods follow the same pattern as GET and POST. ```python r = niquests.put('https://httpbin.org/put', data={'key': 'value'}) r = niquests.delete('https://httpbin.org/delete') r = niquests.head('https://httpbin.org/get') r = niquests.options('https://httpbin.org/get') ``` -------------------------------- ### Synchronous WebSocket Interaction Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates basic interaction with a WebSocket echo server using a synchronous Session. Ensure the `niquests[ws]` extra is installed. ```python from niquests import Session with Session() as s: resp = s.get( "wss://echo.websocket.org", ) print(resp.status_code) # it says "101", for "Switching Protocol" print(resp.extension.next_payload()) # unpack the next message from server resp.extension.send_payload("Hello World") # automatically sends a text message to the server print(resp.extension.next_payload() == "Hello World") # output True! resp.extension.close() # don't forget this call to release the connection! ``` -------------------------------- ### Define Custom Authentication (PizzaAuth) Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Implement a custom authentication mechanism by subclassing `AuthBase`. This example adds a custom 'X-Pizza' header for authentication. ```python from niquests.auth import AuthBase class PizzaAuth(AuthBase): """Attaches HTTP Pizza Authentication to the given Request object.""" def __init__(self, username): # setup any auth-related data here self.username = username def __call__(self, r): # modify and return the request r.headers['X-Pizza'] = self.username return r ``` -------------------------------- ### Executing a Request with a Single Response Hook Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Shows how to make a GET request and trigger the 'print_url' hook upon receiving the response. The output will be the URL of the request. ```python >>> niquests.get('https://httpbin.org/', hooks={'response': print_url}) https://httpbin.org/ ``` -------------------------------- ### Configure Poetry with environment variable Source: https://github.com/jawah/niquests/blob/main/docs/community/faq.md Alternatively, you can combine the URLLIB3_NO_OVERRIDE environment variable with the POETRY_INSTALLER_NO_BINARY setting to prevent the urllib3-future binary during niquests installation. ```bash $ URLLIB3_NO_OVERRIDE=1 POETRY_INSTALLER_NO_BINARY=urllib3-future poetry add niquests ``` -------------------------------- ### Testing ASGI SSE with Synchronous Session Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Use a synchronous niquests Session to test an ASGI Server-Sent Events endpoint. This example retrieves and prints events. ```python from niquests import Session with Session(app=app) as s: resp = s.get("sse://default/sse-events") while not resp.extension.closed: event = resp.extension.next_payload() if event is None: break print(event) # ServerSentEvent(event='message', data='event 0') ``` -------------------------------- ### Initialize Session with Default Parameters Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Demonstrates initializing a synchronous Session object with various default parameters including params, headers, cookies, auth, proxies, and SSL verification. ```python s = niquests.Session( params={'page': '1'}, headers={'x-test': 'true'}, cookies={'from-my': 'browser'}, auth=('user', 'pass'), proxies={'https': 'http://localhost:3128'}, verify=True, ) ``` -------------------------------- ### Testing WSGI Application with Synchronous Session Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Use a synchronous niquests Session to test a WSGI application. This example makes a GET request and checks the status code and JSON response. ```python from niquests import Session with Session(app=app) as s: resp = s.get("/hello?foo=bar") print(resp.status_code) # 200 print(resp.json()) # {"message": "hello from wsgi"} ``` -------------------------------- ### Basic SSE Stream with Niquests (Sync) Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates how to establish a synchronous connection to an SSE endpoint and process incoming events. ```python import niquests if __name__ == "__main__": r = niquests.post("sse://httpbingo.org/sse") print(r) # output: while r.extension.closed is False: event: niquests.ServerSentEvent = r.extension.next_payload() # ServerSentEvent(event='ping', data='{"id":0,"timestamp":1732857000473}') ``` -------------------------------- ### Demonstrate HTTP/2 Multiplexing Source: https://github.com/jawah/niquests/blob/main/docs/community/faq.md This example demonstrates how to leverage HTTP/2 connections for concurrent requests in a synchronous context without threads or async. It compares the performance of standard requests versus multiplexed requests. ```python from time import time from niquests import Session #: You can adjust it as you want and verify the multiplexed advantage! REQUEST_COUNT = 10 REQUEST_URL = "https://httpbin.org/delay/1" def make_requests(url: str, count: int, use_multiplexed: bool): before = time() responses = [] with Session(multiplexed=use_multiplexed) as s: for _ in range(count): responses.append(s.get(url)) print(f"request {_+1}...OK") print([r.status_code for r in responses]) print( f"{time() - before} seconds elapsed ({'multiplexed' if use_multiplexed else 'standard'})" ) #: Let's start with the same good old request one request at a time. print("> Without multiplexing:") make_requests(REQUEST_URL, REQUEST_COUNT, False) #: Now we'll take advantage of a multiplexed connection. print("> With multiplexing:") make_requests(REQUEST_URL, REQUEST_COUNT, True) ``` -------------------------------- ### Basic SSE Stream with Niquests (Async) Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates how to establish an asynchronous connection to an SSE endpoint and process incoming events using asyncio. ```python import niquests import asyncio async def main() -> None: async with niquests.AsyncSession() as s: r = await s.post("sse://httpbingo.org/sse") print(r) # output: while r.extension.closed is False: print(await r.extension.next_payload()) # ServerSentEvent(event='ping', data='{"id":0,"timestamp":1732857000473}') if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### HTTPX Client Instance vs Niquests Session Instance Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md Shows the difference in creating client instances between HTTPX and Niquests. ```python client = httpx.Client(**kwargs) ``` ```python session = niquests.Session(**kwargs) ``` -------------------------------- ### Asynchronous Session Get Request Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates making an asynchronous GET request using AsyncSession and asyncio.gather. ```python import asyncio from niquests import AsyncSession, Response async def fetch(url: str) -> Response: async with AsyncSession() as s: return await s.get(url) async def main() -> None: tasks = [] for _ in range(10): tasks.append(asyncio.create_task(fetch("https://httpbingo.org/delay/1"))) responses = await asyncio.gather(*tasks) print(responses) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### File Uploads in HTTPX and Niquests Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md Demonstrates how to upload files using both HTTPX and Niquests. Both libraries expect binary file handles for uploads. ```python # HTTPX with open('file.bin', 'rb') as f: httpx.post(url, files={'file': f}) ``` ```python # Niquests with open('file.bin', 'rb') as f: niquests.post(url, files={'file': f}) ``` -------------------------------- ### Install Niquests without overriding urllib3 Source: https://github.com/jawah/niquests/blob/main/docs/user/install.md Install Niquests while keeping the original urllib3 package by preventing urllib3-future from overriding it. ```bash $ URLLIB3_NO_OVERRIDE=1 pip install niquests --no-binary urllib3-future ``` -------------------------------- ### WSGI Testing with httpx Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md Demonstrates how to test a WSGI application using httpx's WSGITransport. ```python from flask import Flask import httpx app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" transport = httpx.WSGITransport(app=app) with httpx.Client(transport=transport, base_url="http://testserver") as client: r = client.get("/") assert r.status_code == 200 assert r.text == "Hello World!" ``` -------------------------------- ### Make a Synchronous GET Request Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Perform a simple synchronous GET request to fetch data from a URL. The response is stored in the 'r' variable. ```python r = niquests.get('https://api.github.com/events') ``` -------------------------------- ### Make an Asynchronous GET Request Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Perform a simple asynchronous GET request using 'aget'. This is suitable for non-blocking operations within an async function. ```python r = await niquests.aget('https://api.github.com/events') ``` -------------------------------- ### ASGI/WSGI Testing with FastAPI's TestClient Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md Demonstrates testing an application using FastAPI's TestClient. ```python from fastapi import TestClient # Assuming 'app' is a defined FastAPI application instance # client = TestClient(app) # response = client.get("/") ``` -------------------------------- ### Set Default Headers and Auth with Session Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Shows how to set default authentication and headers on a synchronous Session object, which are then applied to subsequent requests. ```python s = niquests.Session() s.auth = ('user', 'pass') s.headers.update({'x-test': 'true'}) # both 'x-test' and 'x-test2' are sent s.get('https://httpbin.org/headers', headers={'x-test2': 'true'}) ``` -------------------------------- ### Add Custom Headers to an Async GET Request Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Similar to synchronous requests, custom headers can be added to asynchronous GET requests using the `headers` parameter. ```python url = 'https://api.github.com/some/endpoint' headers = {'user-agent': 'my-app/0.0.1'} r = await niquests.aget(url, headers=headers) ``` -------------------------------- ### Use Multiple Resolvers with Session Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Configure a Session to try a list of resolvers in order, falling back to the next if the previous one fails. ```python from niquests import Session with Session(resolver=["doh+google://", "doh://cloudflare-dns.com"]) as s: resp = s.get("https://httpbingo.org/get") ``` -------------------------------- ### Asynchronous GET Request with Niquests (Streaming) Source: https://github.com/jawah/niquests/blob/main/README.md Shows how to perform an asynchronous GET request with streaming enabled. It highlights the need to await the response text when `stream=True`. ```python import niquests import asyncio async def main() -> None: r = await niquests.aget('https://one.one.one.one', stream=True) print(r) # Output: payload = await r.text # we await text because we set `stream=True`! print(payload) # Output: ... ``` -------------------------------- ### Async Session with Multiplexed Connections Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Shows how to use AsyncSession with multiplexed connections for HTTP/2 onward, including session gathering. ```python import asyncio from niquests import AsyncSession, Response async def fetch(url: str) -> list[Response]: responses = [] async with AsyncSession(multiplexed=True) as s: for _ in range(10): responses.append(await s.get(url)) await s.gather() return responses async def main() -> None: tasks = [] for _ in range(10): tasks.append(asyncio.create_task(fetch("https://httpbingo.org/delay/1"))) responses_responses = await asyncio.gather(*tasks) responses = [item for sublist in responses_responses for item in sublist] print(responses) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### ASGI Testing with Niquests Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md Illustrates how to perform ASGI application testing using Niquests' AsyncSession. ```python # Example for ASGI testing using AsyncSession would go here. # Note: The provided text mentions AsyncSession but doesn't include a code example. # This placeholder indicates where such an example would be placed if available. ``` -------------------------------- ### Install Niquests without urllib3-future binary Source: https://github.com/jawah/niquests/blob/main/docs/community/faq.md To install Niquests while preventing the urllib3-future binary from being used, set the URLLIB3_NO_OVERRIDE environment variable and use the --no-binary flag with pip. ```bash $ URLLIB3_NO_OVERRIDE=1 pip install niquests --no-binary urllib3-future ``` -------------------------------- ### Asynchronous GET Request with Niquests (Non-Streaming) Source: https://github.com/jawah/niquests/blob/main/README.md Illustrates an asynchronous GET request without streaming. It shows that the response text can be accessed directly without awaiting when `stream=False` (default). ```python import niquests import asyncio async def main() -> None: # or... without stream=True r = await niquests.aget('https://one.one.one.one') print(r) # Output: payload = r.text # we don't need to away anything, it's already loaded! print(payload) # Output: ... ``` -------------------------------- ### Other Asynchronous HTTP Methods Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Demonstrates making asynchronous PUT, DELETE, HEAD, and OPTIONS requests using their respective 'a' prefixed methods. ```python r = await niquests.aput('https://httpbin.org/put', data={'key': 'value'}) r = await niquests.adelete('https://httpbin.org/delete') r = await niquests.ahead('https://httpbin.org/get') r = await niquests.aoptions('https://httpbin.org/get') ``` -------------------------------- ### Using Response as a Context Manager Source: https://github.com/jawah/niquests/blob/main/HISTORY.md Response objects can now be used directly in a 'with' statement, simplifying resource management. ```python with requests.get('https://httpbin.org/get') as response: response.raise_for_status() # Process the response here ``` -------------------------------- ### GET Request to Retrieve Commit Data Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Use the GET verb to retrieve specific resource data, such as commit information from the GitHub API. Confirms the status code and prints the content type. ```python >>> import niquests >>> r = niquests.get('https://api.github.com/repos/psf/requests/git/commits/a050faf084662f3a352dd1a941f2c7c9f886d4ad') ``` ```python >>> if r.status_code == niquests.codes.ok: ... print(r.headers['content-type']) ... application/json; charset=utf-8 ``` -------------------------------- ### Synchronous GET Request Source: https://github.com/jawah/niquests/blob/main/README.md Demonstrates how to perform a synchronous GET request using niquests. Includes accessing response status code, headers, encoding, text content, JSON payload, and connection information. ```APIDOC ## Synchronous GET Request ### Description Performs a synchronous GET request to a specified URL and provides access to various response attributes. ### Method `niquests.get(url, **kwargs)` ### Endpoint `https://one.one.one.one` ### Parameters - **url** (string) - Required - The URL to send the GET request to. - **kwargs** - Optional - Additional keyword arguments for the request. ### Request Example ```python import niquests r = niquests.get('https://one.one.one.one') print(r.status_code) print(r.headers['content-type']) print(r.text) print(r.json()) print(r.ocsp_verified) print(r.conn_info.established_latency) ``` ### Response #### Success Response (200) - **status_code** (int) - The HTTP status code of the response. - **headers** (dict) - A dictionary of response headers. - **encoding** (str) - The encoding of the response text. - **text** (str) - The response body as a string. - **json** (dict) - The response body parsed as JSON. - **ocsp_verified** (bool) - Indicates if OCSP verification was successful. - **conn_info.established_latency** (timedelta) - The time it took to establish the connection. #### Response Example ```json { "status_code": 200, "headers": { "content-type": "application/json; charset=utf-8" }, "encoding": "utf-8", "text": "{\"authenticated\": true, ...}", "json": { "authenticated": true, ... }, "ocsp_verified": true, "conn_info.established_latency": "0:00:00.000038" } ``` ``` -------------------------------- ### Check HTTP/3 Support Source: https://github.com/jawah/niquests/blob/main/docs/user/quickstart.md Verify if your environment supports HTTP/3 requests by making a GET request to a known IP address. The response will indicate the protocol used (HTTP/2 or HTTP/3). ```python >>> from niquests import get >>> r = get("https://1.1.1.1") >>> r >>> r = get("https://1.1.1.1") >>> r ``` -------------------------------- ### GET Request to Retrieve Issue Data Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Retrieve details about a specific GitHub issue using a GET request. Parses the response text into a JSON object to access issue properties like 'title' and 'comments'. ```python >>> r = niquests.get('https://api.github.com/repos/psf/requests/issues/482') >>> r.status_code 200 >>> issue = json.loads(r.text) >>> print(issue['title']) Feature any http verb in docs >>> print(issue['comments']) 3 ``` -------------------------------- ### Synchronous GET Request with Niquests Source: https://github.com/jawah/niquests/blob/main/README.md Demonstrates a basic synchronous GET request and accessing response attributes like status code, headers, encoding, and JSON payload. Also shows OCSP verification status and connection latency. ```python import niquests r = niquests.get('https://one.one.one.one') r.status_code 200 r.headers['content-type'] 'application/json; charset=utf-8' r.oheaders.content_type.charset 'utf-8' r.encoding 'utf-8' r.text '{"authenticated": true, ...}' r.json() {'authenticated': True, ...} r r.ocsp_verified True r.conn_info.established_latency datetime.timedelta(microseconds=38) ``` -------------------------------- ### Setting Proxies via Environment Variables Source: https://github.com/jawah/niquests/blob/main/docs/user/advanced.md Configure proxies by setting standard environment variables like `HTTP_PROXY`, `HTTPS_PROXY`, and `ALL_PROXY`. Niquests will automatically pick these up. ```default $ export HTTP_PROXY="http://10.10.1.10:3128" $ export HTTPS_PROXY="http://10.10.1.10:1080" $ export ALL_PROXY="socks5://10.10.1.10:3434" $ python >>> import niquests >>> niquests.get('http://example.org') ``` -------------------------------- ### Async Request Execution Source: https://github.com/jawah/niquests/blob/main/docs/dev/httpx.md To perform an asynchronous GET request in Niquests, use `await niquests.aget(...)`. ```default resp = niquests.get(...) ``` ```default resp = await niquests.aget(...) ```