allegroapi-neo
v1.0.0
Published
TypeScript client library for Allegro REST API
Maintainers
Readme
🛒 Allegro API TypeScript Client
Comprehensive TypeScript client library for the Allegro REST API with full type safety, OAuth2 authentication, and extensive API coverage.
✨ Features
- 🎯 Full TypeScript Support - Complete type definitions with IntelliSense
- 🔐 OAuth2 Authentication - Built-in authentication flow handling
- 📦 Comprehensive Coverage - 85-90% of Allegro API endpoints
- ⚡ Developer Experience - Intuitive API design with consistent patterns
- 🧪 Testing Support - Sandbox environment for safe development
- 📚 Interactive Documentation - Swagger UI with live examples
- 🔄 Modern Standards - Promise-based async operations, ES modules
📖 Documentation
- 📋 Interactive API Documentation - Swagger UI (run
npm run docs) - 🌐 Official Allegro API Docs
- ⚙️ Partner Center
🚀 Quick Start
Installation
npm install allegroapi-neoBasic Setup
import { AllegroClient } from 'allegroapi-neo';
const client = new AllegroClient({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://your-app.com/callback',
sandbox: true // Use sandbox for testing
});Authentication
// 1. Get authorization URL
const authUrl = client.getAuthorizationUrl([
'allegro:api:profile:read',
'allegro:api:orders:read',
'allegro:api:orders:write'
]);
// 2. Redirect user to authUrl and get authorization code
// 3. Exchange code for tokens
const tokens = await client.authenticate(authorizationCode);
// 4. Client is now authenticated and ready to useMaking API Calls
// Get user offers
const offers = await client.offers.getOffers({
limit: 10,
'publication.status': 'ACTIVE'
});
// Get orders
const orders = await client.orders.getOrders({
limit: 5,
'fulfillment.status': 'NEW'
});
// Create a new offer
const newOffer = await client.offers.createOffer({
name: "iPhone 15 Pro 128GB",
categoryId: "1234",
price: { amount: "4999.00", currency: "PLN" },
stock: { available: 5, unit: "UNIT" },
delivery: { shippingRates: { id: "template-1" } }
});
// Upload images
const image = await client.images.uploadImage({
image: imageBuffer,
mimeType: 'image/jpeg'
});
// Track shipments
const tracking = await client.shipping.getTrackingInfo(
'carrier-id',
'tracking-number'
);🎯 Available Resources
Core Resources
- Offers - Create, update, and manage product listings
- Orders - Process and fulfill customer orders
- User - Manage user profile and preferences
- Categories - Browse product category tree
- Billing - Handle billing and payment information
- Messaging - Communicate with buyers
Advanced Resources
- Images - Upload and manage product images
- Shipping - Carrier integration and tracking
- Products - Product catalog management
- Events - Real-time offer and order events
- Additional Services - Service configuration and management
- Size Tables - Size management and recommendations
- Tax - Tax calculation and compliance
- Public Offers - Market research and competitor analysis
📋 API Coverage
| Resource | Coverage | Endpoints | |----------|----------|-----------| | Offers | 95% | 25+ endpoints | | Orders | 90% | 20+ endpoints | | Shipping | 85% | 35+ endpoints | | Products | 80% | 25+ endpoints | | Images | 100% | 10 endpoints | | Tax | 85% | 35+ endpoints | | Size Tables | 90% | 40+ endpoints | | Public Offers | 80% | 30+ endpoints | | Total | 85-90% | 220+ endpoints |
🔧 Configuration
Environment Setup
const client = new AllegroClient({
clientId: process.env.ALLEGRO_CLIENT_ID!,
clientSecret: process.env.ALLEGRO_CLIENT_SECRET!,
redirectUri: process.env.ALLEGRO_REDIRECT_URI!,
sandbox: process.env.NODE_ENV !== 'production',
// Optional: Custom API base URL
apiUrl: 'https://api.allegro.pl',
// Optional: Request timeout (default: 30s)
timeout: 30000,
// Optional: Rate limiting
rateLimit: {
requestsPerMinute: 9000
}
});OAuth2 Scopes
Common scopes you might need:
const scopes = [
'allegro:api:profile:read', // Read user profile
'allegro:api:profile:write', // Update user profile
'allegro:api:orders:read', // Read orders
'allegro:api:orders:write', // Manage orders
'allegro:api:billing:read', // Read billing info
'allegro:api:campaigns:read', // Read ad campaigns
'allegro:api:campaigns:write', // Manage ad campaigns
'allegro:api:fulfillment:read', // Read fulfillment
'allegro:api:fulfillment:write' // Manage fulfillment
];📝 Examples
Complete Order Processing
// Get new orders
const newOrders = await client.orders.getOrders({
'fulfillment.status': 'NEW',
limit: 50
});
for (const order of newOrders.data.checkoutForms) {
// Update fulfillment status
await client.orders.createFulfillment(order.id, {
lineItems: order.lineItems.map(item => ({
offerId: item.offer.id,
quantity: item.quantity
}))
});
// Create shipment
const shipment = await client.shipping.createShipment({
carrierId: 'allegro-courier',
sender: { /* sender details */ },
receiver: order.delivery.address,
packages: [{
weight: { value: 1.5, unit: 'kg' },
dimensions: { length: 20, width: 15, height: 10, unit: 'cm' }
}]
});
// Generate shipping label
const label = await client.shipping.generateLabel(shipment.data.id);
console.log(`Order ${order.id} processed, tracking: ${shipment.data.trackingNumber}`);
}Bulk Price Updates
// Get all active offers
const offers = await client.offers.getOffers({
'publication.status': 'ACTIVE',
limit: 1000
});
// Prepare bulk price updates
const priceUpdates = offers.data.offers.map(offer => ({
id: offer.id,
price: {
amount: (parseFloat(offer.price.amount) * 1.1).toFixed(2), // 10% increase
currency: offer.price.currency
}
}));
// Execute bulk update using pricing commands
for (const update of priceUpdates) {
await client.pricing.createPricingCommand({
offer: { id: update.id },
price: update.price
});
}Market Research
// Search competitor offers
const competitors = await client.publicOffers.searchPublicOffers({
phrase: 'iPhone 15 Pro',
category: '1234',
priceFrom: '4000.00',
priceTo: '6000.00',
sort: 'PRICE',
limit: 50
});
// Analyze market position
const analysis = await client.publicOffers.getMarketAnalysis('your-offer-id', {
includeCompetitors: true,
includeTrends: true,
period: '30d'
});
console.log('Market insights:', analysis.data);🧪 Development
Running Documentation
Start the interactive Swagger UI documentation:
npm run docsVisit http://localhost:3001 to explore the API documentation with live examples.
Building the Project
npm run build # Build TypeScript
npm run typecheck # Type checking only
npm run lint # ESLint
npm run test # Run tests🔐 Authentication Flow
The library handles the complete OAuth2 authorization code flow:
- Authorization Request - Generate authorization URL
- User Consent - User authorizes your application
- Code Exchange - Exchange authorization code for tokens
- Token Management - Automatic token refresh and storage
// Step 1: Generate authorization URL
const authUrl = client.getAuthorizationUrl(scopes);
// Step 2: User visits authUrl and authorizes
// Step 3: Extract code from callback and authenticate
const tokens = await client.authenticate(authorizationCode);
// Step 4: Store tokens securely (optional)
localStorage.setItem('allegro_tokens', JSON.stringify(tokens));
// Step 5: Restore tokens on app restart
const savedTokens = JSON.parse(localStorage.getItem('allegro_tokens') || '{}');
if (savedTokens.access_token) {
client.setTokens(savedTokens);
}⚠️ Error Handling
The library provides comprehensive error handling with typed error responses:
try {
const offers = await client.offers.getOffers();
} catch (error) {
if (error.response?.status === 401) {
// Token expired - refresh or re-authenticate
console.log('Authentication required');
} else if (error.response?.status === 429) {
// Rate limit exceeded
console.log('Rate limit exceeded, retry after:', error.response.headers['retry-after']);
} else if (error.response?.data?.errors) {
// API validation errors
error.response.data.errors.forEach(err => {
console.log(`Error: ${err.message} (${err.code})`);
});
} else {
console.log('Unexpected error:', error.message);
}
}🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
Made with ❤️ for the Allegro developer community
