1️⃣ What is Axios?
Axios is a promise-based HTTP client for JavaScript.
Works in browser and Node.js environments.
Supports:
GET, POST, PUT, DELETE, PATCH requests
Request/response interceptors
Automatic JSON parsing
Error handling
Canceling requests
Ideal for communicating with a Python REST API.
2️⃣ Setting Up Axios
If your front-end is using npm or yarn:
# Using npm
npm install axios
# Using yarn
yarn add axios
For plain HTML/JS, you can include via CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
3️⃣ Basic Usage of Axios
GET Request
import axios from 'axios';
axios.get('http://localhost:5000/api/users')
.then(response => {
console.log(response.data); // Data from Python API
})
.catch(error => {
console.error('Error fetching users:', error);
});
POST Request
axios.post('http://localhost:5000/api/users', {
name: 'John Doe',
email: 'john@example.com'
})
.then(response => {
console.log('User created:', response.data);
})
.catch(error => {
console.error('Error creating user:', error);
});
PUT Request
axios.put('http://localhost:5000/api/users/1', {
name: 'John Smith'
})
.then(response => {
console.log('User updated:', response.data);
})
.catch(error => {
console.error('Error updating user:', error);
});
DELETE Request
axios.delete('http://localhost:5000/api/users/1')
.then(response => {
console.log('User deleted:', response.data);
})
.catch(error => {
console.error('Error deleting user:', error);
});
4️⃣ Axios with Async/Await
Using async/await makes Axios calls cleaner and easier to read.
async function fetchUsers() {
try {
const response = await axios.get('http://localhost:5000/api/users');
console.log(response.data);
} catch (error) {
console.error('Error fetching users:', error);
}
}
fetchUsers();
5️⃣ Handling Python Back-End Responses
Assume a Python Flask API:
from flask import Flask, jsonify, request
app = Flask(__name__)
users = []
@app.route('/api/users', methods=['GET'])
def get_users():
return jsonify(users)
@app.route('/api/users', methods=['POST'])
def add_user():
data = request.get_json()
users.append(data)
return jsonify(data), 201
if __name__ == '__main__':
app.run(debug=True)
Axios automatically parses JSON responses.
Python API should return proper status codes (200 OK, 201 Created, 404 Not Found, etc.).
Axios can handle these codes in .then or try/catch blocks.
6️⃣ Setting Headers and Authentication
Custom Headers
axios.get('http://localhost:5000/api/users', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json'
}
});
Sending JSON Data
axios.post('http://localhost:5000/api/users',
{ name: 'Alice', email: 'alice@example.com' },
{ headers: { 'Content-Type': 'application/json' } }
);
Handling JWT or Tokens
Store JWT in localStorage or cookies.
Attach token to headers for authentication.
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
7️⃣ Axios Interceptors
Interceptors allow you to handle requests/responses globally.
Request Interceptor
axios.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
}, error => {
return Promise.reject(error);
});
Response Interceptor
axios.interceptors.response.use(response => {
return response;
}, error => {
if (error.response.status === 401) {
// Handle unauthorized access
console.log('Unauthorized! Redirect to login.');
}
return Promise.reject(error);
});
8️⃣ Handling Errors in Axios
Axios provides rich error objects:
error.response: Response from the server (status code, data)
error.request: Request made but no response
error.message: Error message
try {
await axios.get('http://localhost:5000/api/users');
} catch (error) {
if (error.response) {
console.error('Server responded with:', error.response.status);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error setting up request:', error.message);
}
}
9️⃣ Best Practices in Full-Stack Python Projects
Use Base URLs:
const api = axios.create({
baseURL: 'http://localhost:5000/api'
});
Makes endpoints easier to maintain.
Handle Timeouts:
axios.get('/users', { timeout: 5000 });
Centralize Error Handling:
Use response interceptors to manage global errors, like 401 Unauthorized or 500 Server Error.
Use Async/Await for Readability:
Promises work fine, but async/await makes full-stack code cleaner.
Secure API Communication:
Always use HTTPS in production.
Attach JWT tokens or API keys via headers.
Avoid storing sensitive tokens in localStorage without security precautions.
Enable CORS in Python API:
If front-end is hosted separately, ensure your Python back-end allows cross-origin requests:
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
🔹 Summary
Axios is a powerful, promise-based HTTP client for front-end communication with Python back-ends.
Supports all HTTP methods, async/await, interceptors, and custom headers.
Ideal for full-stack projects (React + Flask/Django/FastAPI).
Combine Axios with secure API design, JWT auth, and proper error handling for robust front-end/back-end interaction.
Learn Fullstack Python Training in Hyderabad
Read More
How to Handle API Data in React with Python Backend
Building Real-Time Web Applications with WebSockets in Python
How to Use AJAX with Python for Seamless User Interactions
Connecting Flask with React: Building a Full Stack App
At Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments