AutoRest swagger generator Python client runtime for REST API clients with serialization, authentication, and request handling.
—
Client configuration management including base URL settings, authentication credentials, HTTP policies, pipeline configuration, and connection parameters. The Configuration class centralizes all client settings and provides the foundation for the service client's HTTP pipeline.
Create and initialize client configuration with base URL and optional settings file.
class Configuration:
def __init__(self, base_url: str, filepath=None):
"""
Initialize client configuration.
Parameters:
- base_url: REST API base URL
- filepath: Optional path to config file
"""
base_url: str
credentials: any = None
keep_alive: bool = False
pipeline: anyConfigure and manage the User-Agent header for HTTP requests.
@property
def user_agent(self) -> str:
"""Get current user agent string."""
def add_user_agent(self, value: str):
"""
Add value to current user agent.
Parameters:
- value: String to append to user agent
"""
user_agent_policy: any # UserAgentPolicy instanceConfigure HTTP request and response logging for debugging and monitoring.
@property
def enable_http_logger(self) -> bool:
"""Get HTTP logging enabled status."""
@enable_http_logger.setter
def enable_http_logger(self, value: bool):
"""
Enable or disable HTTP logging.
Parameters:
- value: True to enable, False to disable
"""
http_logger_policy: any # HTTPLogger instanceLoad configuration settings from external files.
def load(self, filepath: str):
"""
Load configuration from file.
Parameters:
- filepath: Path to configuration file
"""The Configuration class inherits from RequestHTTPSenderConfiguration, providing HTTP-specific settings:
# Connection settings
connection: any # Connection configuration object
timeout: int # Request timeout in seconds
verify: bool # SSL certificate verification
proxies: dict # Proxy configuration
headers: dict # Default headers for all requests
# SSL/TLS settings
cert: any # Client certificate configuration
stream: bool # Enable response streaming
allow_redirects: bool # Follow HTTP redirects
max_redirects: int # Maximum redirect count
# Data handling
data_block_size: int # Block size for streaming operationsfrom msrest import Configuration
# Create basic configuration
config = Configuration(base_url='https://api.example.com')
# Set authentication
from msrest.authentication import ApiKeyCredentials
config.credentials = ApiKeyCredentials(in_headers={'X-API-Key': 'your-key'})
# Configure User-Agent
config.add_user_agent('MyApp/1.0')
print(config.user_agent) # Shows current user agent stringfrom msrest import Configuration
config = Configuration(base_url='https://api.example.com')
# Configure HTTP settings
config.timeout = 30 # 30 second timeout
config.verify = True # Verify SSL certificates
config.allow_redirects = True
config.max_redirects = 5
# Set default headers
config.headers = {
'Accept': 'application/json',
'User-Agent': 'MyApp/1.0'
}
# Configure proxy
config.proxies = {
'http': 'http://proxy.example.com:8080',
'https': 'https://proxy.example.com:8080'
}from msrest import Configuration
import logging
# Enable HTTP logging
config = Configuration(base_url='https://api.example.com')
config.enable_http_logger = True
# Configure Python logging to see HTTP logs
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('msrest.http_logger')
logger.setLevel(logging.DEBUG)from msrest import Configuration
config = Configuration(base_url='https://api.example.com')
# Disable SSL verification (not recommended for production)
config.verify = False
# Use custom CA bundle
config.verify = '/path/to/ca-bundle.crt'
# Client certificate authentication
config.cert = '/path/to/client.pem'
# Or with separate key file
config.cert = ('/path/to/client.crt', '/path/to/client.key')from msrest import Configuration
# Create config and load from file
config = Configuration(base_url='https://api.example.com')
config.load('/path/to/config.ini')
# Or load during initialization
config = Configuration(
base_url='https://api.example.com',
filepath='/path/to/config.ini'
)Example configuration file format (INI):
[connection]
timeout = 30
verify = true
allow_redirects = true
[proxy]
http = http://proxy.example.com:8080
https = https://proxy.example.com:8080
[headers]
Accept = application/json
User-Agent = MyApp/1.0from msrest import ServiceClient, Configuration
# Enable keep-alive for connection reuse
config = Configuration(base_url='https://api.example.com')
config.keep_alive = True
# Use with context manager for automatic cleanup
with ServiceClient(None, config) as client:
# Connection will be kept alive for multiple requests
response1 = client.send(client.get('/endpoint1'))
response2 = client.send(client.get('/endpoint2'))
# Connection automatically closed when exiting contextfrom msrest import Configuration
from msrest.pipeline import HTTPPolicy
class CustomHeaderPolicy(HTTPPolicy):
def send(self, request, **kwargs):
request.http_request.headers['X-Custom-Header'] = 'MyValue'
return self.next.send(request, **kwargs)
# Add custom policy to pipeline
config = Configuration(base_url='https://api.example.com')
# Pipeline will be created when ServiceClient is initialized
# Custom policies can be added through the pipeline propertyfrom msrest import Configuration
config = Configuration(base_url='https://api.example.com')
# Configure streaming settings
config.stream = True # Enable response streaming
config.data_block_size = 8192 # 8KB blocks for streaming
# Use with large file downloads
from msrest import ServiceClient
with ServiceClient(None, config) as client:
request = client.get('/large-file')
response = client.send(request, stream=True)
# Stream the response
for chunk in client.stream_download(response, callback=None):
# Process chunk
passimport os
from msrest import Configuration
from msrest.authentication import BasicAuthentication
# Load settings from environment variables
base_url = os.getenv('API_BASE_URL', 'https://api.example.com')
username = os.getenv('API_USERNAME')
password = os.getenv('API_PASSWORD')
config = Configuration(base_url=base_url)
if username and password:
config.credentials = BasicAuthentication(username, password)
# Configure from environment
config.timeout = int(os.getenv('API_TIMEOUT', '30'))
config.verify = os.getenv('API_VERIFY_SSL', 'true').lower() == 'true'
if os.getenv('HTTP_PROXY'):
config.proxies = {
'http': os.getenv('HTTP_PROXY'),
'https': os.getenv('HTTPS_PROXY', os.getenv('HTTP_PROXY'))
}Configuration objects are passed to ServiceClient during initialization:
from msrest import ServiceClient, Configuration
# Create configuration
config = Configuration(base_url='https://api.example.com')
# Configure as needed
config.timeout = 30
config.enable_http_logger = True
# Create client with configuration
client = ServiceClient(None, config)
# Or use as context manager
with ServiceClient(None, config) as client:
# Client will use all configuration settings
response = client.send(client.get('/data'))The ServiceClient will use the configuration to:
Install with Tessl CLI
npx tessl i tessl/pypi-msrest