Authentication overview
The National Bank of Poland (NBP) provides public access to its API for retrieving official exchange rates, gold prices, and interest rates without requiring explicit authentication credentials such as API keys, OAuth tokens, or client secrets. This design simplifies integration for developers and applications that need to consume NBP's publicly available financial data.
The NBP API is designed for read-only access to economic data, making traditional authentication mechanisms less critical compared to APIs that handle sensitive user data or perform transactional operations. Data is served over HTTPS to ensure transport layer security, protecting against eavesdropping and tampering during transit.
While direct authentication is not required, client applications are still expected to adhere to standard web practices, including proper request formatting and respectful query frequency to avoid overloading the service. The NBP documentation outlines the structure for API calls, allowing developers to retrieve specific currency tables (A, B, C) and historical data points directly from the NBP servers.
Supported authentication methods
The National Bank of Poland API operates on a public access model, meaning it does not support or require conventional authentication methods for accessing its core datasets, including official exchange rates and gold prices. This approach differs from many commercial APIs that implement schemes like OAuth 2.0 or API key-based authentication for rate limiting, user identification, or access control to premium features.
Instead, access is granted based on direct HTTP requests. The API relies on the security benefits of HTTPS to encrypt communication, ensuring that data exchanged between the client and the NBP server remains confidential and integral during transit. This reliance on transport layer security is a fundamental aspect of secure web communication, as detailed in web security guidelines for protecting data in transit.
The following table summarizes the access model:
| Method | When to Use | Security Level |
|---|---|---|
| Direct HTTP Request (via HTTPS) | Accessing all public NBP API endpoints (e.g., currency rates, gold prices). | Transport Layer Security (TLS 1.2+). Data is encrypted in transit. |
Due to the public nature of the data and the absence of user-specific or transactional operations, the NBP API does not implement methods such as OAuth 2.0 for delegated authorization or API keys for client identification. This design simplifies the integration process significantly, as developers do not need to manage credentials or implement complex authentication flows within their applications.
Getting your credentials
As the National Bank of Poland API provides open access to its public datasets, there are no specific credentials (such as API keys, client IDs, or secrets) that need to be obtained or configured. Developers can begin making requests to the NBP API endpoints immediately after familiarizing themselves with the API documentation.
The process involves constructing the correct URL for the desired data, such as daily exchange rates for a specific currency or historical gold prices. The NBP API documentation provides comprehensive details on the available endpoints and required URL parameters to fetch the relevant information.
For example, to retrieve the current exchange rate for a given currency from table A, a developer would construct a URL like https://api.nbp.pl/api/exchangerates/rates/a/usd/. There is no need to embed any form of authentication token or header in these requests.
Developers are encouraged to review the official NBP API reference to understand the various endpoints and data structures. This resource provides all necessary information for successful integration without requiring a registration or credential generation process.
Authenticated request example
Since the National Bank of Poland API does not require explicit authentication, an "authenticated" request is simply a direct HTTP GET request to the appropriate API endpoint using HTTPS. Below are examples in Python and JavaScript demonstrating how to fetch data from the NBP API without any authentication headers or tokens.
Python example
This Python example uses the requests library to fetch the current average exchange rate for USD from NBP's Table A.
import requests
import json
url = "https://api.nbp.pl/api/exchangerates/rates/a/usd/"
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
# Process the data
if data and 'rates' in data and len(data['rates']) > 0:
currency_name = data['currency']
code = data['code']
rate = data['rates'][0]['mid']
effective_date = data['rates'][0]['effectiveDate']
print(f"Current {currency_name} ({code}) exchange rate: {rate} PLN (as of {effective_date})")
else:
print("No rates found for USD.")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An unexpected error occurred: {req_err}")
except json.JSONDecodeError:
print("Error decoding JSON response.")
JavaScript (Node.js) example
This Node.js example uses the built-in https module to perform a GET request for the current average exchange rate for EUR from NBP's Table A.
const https = require('https');
const url = 'https://api.nbp.pl/api/exchangerates/rates/a/eur/';
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
try {
const result = JSON.parse(data);
if (result && result.rates && result.rates.length > 0) {
const currencyName = result.currency;
const code = result.code;
const rate = result.rates[0].mid;
const effectiveDate = result.rates[0].effectiveDate;
console.log(`Current ${currencyName} (${code}) exchange rate: ${rate} PLN (as of ${effectiveDate})`);
} else {
console.log('No rates found for EUR.');
}
} catch (e) {
console.error('Error parsing JSON:', e);
}
} else {
console.error(`Request failed with status code: ${res.statusCode}`);
}
});
}).on('error', (err) => {
console.error('Error during request:', err.message);
});
Both examples demonstrate direct API calls without any authentication parameters, headers, or tokens. The focus is on handling the HTTP response and parsing the JSON data returned by the NBP API.
Security best practices
Even though the National Bank of Poland API does not require explicit authentication, adhering to general security best practices for API consumption is critical to ensure the reliability and integrity of your application. These practices focus on secure data handling, robust error management, and responsible API usage.
- Always use HTTPS: The NBP API serves data exclusively over HTTPS. Always ensure your client applications enforce HTTPS to protect data in transit from eavesdropping and tampering. This is a fundamental layer of security for any web communication, as highlighted in Mozilla's explanation of HTTPS.
- Validate input and output: Before using data received from the NBP API, validate its structure and content to prevent unexpected behavior or security vulnerabilities like injection attacks if the data is subsequently used in dynamic queries or displayed on a webpage. Similarly, sanitize any user input that might be used to construct API requests.
- Implement robust error handling: Design your application to gracefully handle various HTTP status codes (e.g., 404 Not Found, 429 Too Many Requests, 500 Internal Server Error) and network issues. This prevents application crashes and provides a better user experience.
- Manage request frequency: While the NBP API does not enforce strict rate limits via authentication, it is good practice to avoid excessive request volumes that could impact service availability. Implement caching mechanisms for frequently requested data to reduce the load on the NBP servers.
- Secure your application environment: Ensure the environment where your application runs is secure. This includes keeping operating systems and libraries updated, using strong access controls for servers, and protecting source code repositories.
- Monitor API usage: Log API requests and responses to monitor for anomalies, detect potential abuse, and aid in debugging. This can help identify if your application is making unintended requests or experiencing issues with data retrieval.
- Consider data integrity: For critical applications, consider implementing checksums or other data integrity checks if the NBP provided such mechanisms. Though not explicitly available for NBP, for other APIs, this can verify that the data has not been altered since it was provided by the source.
- Avoid hardcoding URLs: Although the NBP API URL is stable, for maintainability and flexibility, store API base URLs in configuration files rather than hardcoding them directly into your application logic.
By following these best practices, developers can create secure, resilient, and efficient applications that integrate effectively with the National Bank of Poland's public API endpoints.