Skip to content
Share
Explore
Postman

icon picker
Ejemplo

Variables de entorno

Dentro de las variables de entorno en Postman, almacenamos información que puede ser adaptada automáticamente según la configuración del entorno seleccionado.

enviroment.png
En este caso, mi entorno local está configurado de la siguiente manera. Sin embargo, la definición de las variables es la misma en todos los entornos; lo que varía es su valor.
variables.png
info-squared
El username y el password podrían estar en las variables globales, siempre y cuando el usuario de acceso sea el mismo para todos los entornos.

Uso de las variables de entorno.

En la solicitud, las variables se llaman entre llaves en la etiqueta body.
login.png

Variables de coleccion

Las variables de colección son útiles para solicitudes y pruebas individuales dentro de cada colección.
collection.png
info
He dejado idSection e idCourse así porque me interesa probar que la API funcione correctamente. De esta manera, no tengo que buscar en la base de datos qué sección tiene acceso el usuario logueado. Para obtener estos valores, utilizo los scripts previos a la solicitud (pre-request scripts).

Pre-request Script.

Se puede ejecutar un script pre-request tanto a nivel de colección como a nivel de solicitud, según las necesidades específicas que surjan.
function parseJwt() {
const token = pm.environment.get("token");

if (!token) {
console.log('Token is empty or not defined.');
return null; // Devuelve null si el token no está presente o es vacío
}

try {
let base64Url = token.split('.')[1];
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));

return JSON.parse(jsonPayload);
} catch (error) {
console.error('Error parsing JWT:', error);
return null; // Devuelve null si hay un error al decodificar el token
}
}


function getTokenExpirationDate() {
const decoded = parseJwt();

// Verificar si decoded es null o undefined
if (!decoded || decoded.exp === undefined) {
console.log('Token is not present or could not be parsed.');
return null;
}

const date = new Date(0);
date.setUTCSeconds(decoded.exp);

return date;
}

function isTokenValid() {
const expirationDate = getTokenExpirationDate();
if (expirationDate === null) {
console.log('Token does not have an expiration date.');
return false;
}

const currentDate = new Date();
if (currentDate < expirationDate) {
console.log('Token is valid.');
return true;
} else {
console.log('Token has expired.');
return false;
}
}

function login() {
pm.sendRequest({
url: pm.environment.get("url") + "/api/login",
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({
email: pm.environment.get("username"),
password: pm.environment.get("password")
})
}
}, function (err, res) {
if (err) {
console.error(err);
} else {
const body = res.json();
const token = body.data?.token;
pm.environment.set("token", token);
console.log('New token acquired and set in environment.', token);

// Retry the original request after obtaining the new token
pm.request.headers.upsert({ key: 'Authorization', value: 'Bearer ' + token });
pm.sendRequest(pm.request, function (err, res) {
if (err) {
console.error('Retrying request failed:', err);
} else {
console.log('Original request retried successfully after refreshing token.');
}
});
}
});
}

// First, check if the token is valid
const valid = isTokenValid();


async function obtainSection() {
try {
const response = await new Promise((resolve, reject) => {
pm.sendRequest({
url: pm.environment.get("url") + "/api/sections",
method: 'GET',
header: {
'Authorization': 'Bearer ' + pm.environment.get("token")
}
}, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});

const body = response.json();

const sections = body.data.sections;
if (sections.length === 0) {
throw new Error("No sections found.");
}
const section = sections[0];

pm.variables.set("idSection", section.id);
} catch (error) {
console.error(error);
}
}

// Function to get details of a section
async function detailSection() {
try {
const sectionId = pm.variables.get("idSection");
if (!sectionId) {
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.