No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Curso Profesional de Next.js

Curso Profesional de Next.js

Oscar Barajas Tavares

Oscar Barajas Tavares

Presentación de la API

10/31
Recursos

Aportes 12

Preguntas 4

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

Todos los endpoints que habían en el swager a la fecha, por si desean tomarlos, recuerden siempre revisar que no haya un typo o algo por el estilo.

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endPoints = {
  products:{
    getProducts: `${API}/api/${VERSION}/products/`,
    postProducts: `${API}/api/${VERSION}/products/`,
    getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
    putProducts: (id) => `${API}/api/${VERSION}/products/${id}`,
    deleteProducts: (id) => `${API}/api/${VERSION}/products/${id}`
  },
  users:{
    getUsers: `${API}/api/${VERSION}/users`,
    postUsers: `${API}/api/${VERSION}/users`,
  },  
  auth: {
    login: `${API}/api/${VERSION}/auth/login`,
    profile: `${API}/api/${VERSION}/auth/profile`
  },
  categories:{
    getCategories: `${API}/api/${VERSION}/categories`,
    postCategories: `${API}/api/${VERSION}/categories`,
    getCategoriesProduct: (id) => `${API}/api/${VERSION}/categories/${id}/products`,
    putCategories: (id) => `${API}/api/${VERSION}/categories/${id}`,
  },
  files:{
    postFiles: `${API}/api/${VERSION}/files/upload`,
    getFiles: (fileName) => `${API}/api/${VERSION}/${fileName}`
  }
  
}

export default endPoints

Clase #10: Presentación de la API 10/31 💾


 

¿Qué es una API?

 

Las API son conjuntos de definiciones y protocolos que se utilizan para diseñar e integrar el software de las aplicaciones. Suele considerarse como el contrato entre el proveedor de información y el usuario, donde se establece el contenido que se necesita por parte del consumidor (la llamada) y el que requiere el productor (la respuesta). Fuente: aquí

 


 

Continuando con el Proyecto: 🔨

 
Vamos a usar la url de la API del proyecto (puedes usar otra API d tu preferencia). En el archivo .env.local se agrega:

NEXT_PUBLIC_API_URL=https://api.escuelajs.co

Y para estandarizar la versión de la API agregamos:

NEXT_PUBLIC_API_VERSION=v1

 
En src creamos la carpeta services, dentro creamos la carpeta api, dentro creamos el archivo index.js aquí vamos a construir el diccionario que va a tener todos los puntos entradas claves para la estructura del llamado y actualización del producto, usuario, etc.
 
Por ejemplo con files, dentro de la url de la API nos indica que podemos manejar dos tipos de llamados: GET y POST, por lo general nos interesa actualizar un archivo como una imagen en la API por lo que implementaremos la petición POST, en la página nos indica que para hacer la petición usemos la url: https://api.escuelajs.co/api/v1/files/upload/
 
Podemos desfragmentar la dirección y para https://api.escuelajs.co/ sería igual a ${API}, en cuanto a la versión v1 sería igual a ${VERSION}, de modo que el llamado dentro de comillas simples invertidas queda:

${API}/api/${VERSION}/files/upload/

 
Para cada petición en la API podemos crear las correspondientes funciones a los diferentes llamados, tomar en cuenta las entradas:

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endPoints = {
	auth:{
		login: `${API}/api/${VERSION}/auth/login`, //Se copia desde la página de la API la ruta para el punto de entrada de login
		profile: `${PI}/api/${VERSION}/auth/profile`,
	},
	products:{
		getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
		//Tomar en cuenta que para agregar producto la url necesita de dos entradas: limit y offset
		getProducts: (limit, offset) => `${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,
		addProducts: `${API}/api/${VERSION}/products`,
		updateProducts: (id) => `${API}/api/${VERSION}/products/${id}/`,
		deleteProducts: (id) => `${API}/api/${VERSION}/products/${id}/`,
	},
	categories:{
		getCategoriesList: `${API}/api/${VERSION}/categories/`,
		addCategory: `${API}/api/${VERSION}/categories/`,
		getCategoryItems: (id) => `${API}/api/${VERSION}/categories/${id}/products/`,
		updateCategory: (id) => `${API}/api/${VERSION}/categories/${id}/`,
	},
	files: {
		addImage: `${API}/api/${VERSION}/files/upload/`,
	},
};

export default endPoints;

 
Creamos un archivo como referencia para subirlo al repositorio, lo llamamos: .env-example y agregamos:

TAILWIND_MODE=
NEXT_PUBLIC_API_URL=
NEXT_PUBLIC_API_VERSION=

El reto de la clase:

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endpoints = {
    auth: {
        login: `${API}/${VERSION}/auth/login`,
        profile: `${API}/${VERSION}/auth/profile`,
    },
    categories: {
        list: `${API}/${VERSION}/categories`,
        create: `${API}/${VERSION}/categories`,
        get: (id) => `${API}/${VERSION}/categories/${id}`,
        update: (id) => `${API}/${VERSION}/categories/${id}`,
        categoryProducts: (id) => `${API}/${VERSION}/categories/${id}/products`,
    },
    files: {
        upload: `${API}/${VERSION}/files/upload`,
        get: (filename) => `${API}/${VERSION}/files/${filename}`,
    },
    products: {
        list: `${API}/${VERSION}/products`,
        paginate: (limit = 10, offset = 1) => `${API}/${VERSION}/products?limit=${limit}&offset=${offset}`,
        get: (id) => `${API}/${VERSION}/products/${id}`,
        create: `${API}/${VERSION}/products`,
        update: (id) => `${API}/${VERSION}/products/${id}`,
        delete: (id) => `${API}/${VERSION}/products/${id}`,
    },
    users: {
        list: `${API}/${VERSION}/users`,
        create: `${API}/${VERSION}/users`,
        isAvailable: `${API}/${VERSION}/users/is-available/`,
    },
};

export default endpoints;

Hace poco NextJS facilito las variables de entorno, ahora puedes usarla de la siguiente manea si el archivo .env o .env.local no te esta funcionando:

En el archivo next.config.js agregamos la siguiente linea:

module.exports = {
  env: {
    apiPublicUrl: '(Tu URL)',
  },
}

cuando llames a este endpoint o variable de entorno seria de la siguiente forma:

`${process.env.apiPublicUrl}` (con comillas francesas)

Mas información al respecto: en la pagina oficial de Next JS

Reto de la clase

export const endPoints = {
	auth: {
		login: `${API}/api/${VERSION}/auth/login`,
		profile: `${API}/api/${VERSION}/auth/profile`,
		refreshToken: `${API}/api/${VERSION}/auth/refresh-token`,
	},
	products: {
		getAll: (limit = 0, offset = 0) =>
			`${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,
		post: `${API}/api/${VERSION}/products`,
		get: (id) => `${API}/api/${VERSION}/products/${id}`,
		put: (id) => `${API}/api/${VERSION}/products/${id}`,
		delete: (id) => `${API}/api/${VERSION}/products/${id}`,
	},
	users: {
		getAll: (limit) => `${API}/api/${VERSION}/users?limit=${limit}`,
		post: `${API}/api/${VERSION}/users`,
		get: (id) => `${API}/api/${VERSION}/user/${id}`,
		put: (id) => `${API}/api/${VERSION}/user/${id}`,
		delete: (id) => `${API}/api/${VERSION}/user/${id}`,
		available: `${API}/api/${VERSION}/user/is-available`,
	},
	categories: {
		getAll: `${API}/api/${VERSION}/categories`,
		post: `${API}/api/${VERSION}/categories`,
		get: (id) => `${API}/api/${VERSION}/categories/${id}`,
		put: (id) => `${API}/api/${VERSION}/categories/${id}`,
		delete: (id) => `${API}/api/${VERSION}/categories/${id}`,
		products: (id) => `${API}/api/${VERSION}/categories/${id}/products`,
	},
	files: {
		upload: `${API}/api/${VERSION}/files/upload`,
		get: (filename) => `${API}/api/${VERSION}/files/${filename}`,
	},
};

Solucion

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endpoints = {
  auth: {
    login: `${API}/api/${VERSION}/auth/login`,
    profile: `${API}/api/${VERSION}/auth/profile`,
  },
  products: {
    getList: (limit, offset) => `${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,
    getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
    postProduct: `${API}/api/${VERSION}/products`,
    putProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
    deleteProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
  },
  users: {
    getList: (limit) => `${API}/api/${VERSION}/users?limit=${limit}`,
    postUser: `${API}/api/${VERSION}/users`,
    isAvailable: `${API}/api/${VERSION}/users/is-available`,
  },
  categories: {
    getList: (limit) => `${API}/api/${VERSION}/categories?limit=${limit}`,
    postCategory: `${API}/api/${VERSION}/categories`,
    getCategory: (id) => `${API}/api/${VERSION}/categories/${id}`,
    putCategory: (id) => `${API}/api/${VERSION}/categories/${id}`,
    getProductsByCategorie: (id) => `${API}/api/${VERSION}/categories/${id}/products`,
  },
  files: {
    upload: `${API}/api/${VERSION}/files/upload`,
    getFile: (filename) => `${API}/api/${VERSION}/files/${filename}`,
  }
};

export default endpoints;

La actividad del final de clase:

const API = process.env.NEXT_PUBLIC_API_URL
const API_VERSION = process.env.NEXT_PUBLIC_API_VERSION

const endPoints = {
  auth: {
    login: `${API}/${API_VERSION}/auth/login`,
    profile: `${API}/${API_VERSION}/auth/profile`,
  },
  products: {
    products: (limit = 10, offset = 0) => `${API}/${API_VERSION}/products?limit=${limit}&offset=${offset}`,
    product: id => `${API}/${API_VERSION}/products/${id}`,
  },
  users: {
    users: `${API}/${API_VERSION}/users`,
    isAvailable: `${API}/${API_VERSION}/users/is-available`,
  },
  categories: {
    categories: `${API}/${API_VERSION}/categories`,
    category: id => `${API}/${API_VERSION}/categories/${id}`,
  },
  files: {
    uploadFile: `${API}/${API_VERSION}/files/upload`,
    file: fileName => `${API}/${API_VERSION}/files/${fileName}`,
  }
}

Al hacer el reto VERIFIQUEN LOS SLASH !importante/

    getCategoryItems: (id) => `${API}/api/${VERSION}/categories/${id}/products/`,

Importante el slash final products/

Este es el reto cumplido funcional

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endPoints = {
	  auth: {
    login: `${API}/api/${VERSION}/auth/login`,
    profile: `${API}/api/${VERSION}/auth/profile`,
  },
  products: {
    getProduct: (id) => `${API}/api/${VERSION}/products/${id}/`,
		getProducts: (limit, offset) => `${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,
    addProducts: `${API}/api/${VERSION}/products`,
    updateProduct: (id) => `${API}/api/${VERSION}/products/${id}/`,
    deleteProducts: (id) => `${API}/api/${VERSION}/products/${id}/`,
  },

  categories: {
    getCategoriesList: `${API}/api/${VERSION}/categories/`,
    addCategory: `${API}/api/${VERSION}/categories/`,
    getCategoryItems: (id) => `${API}/api/${VERSION}/categories/${id}/products/`,
    updateCategory: (id) => `${API}/api/${VERSION}/categories/${id}/`,
  },

  files: {
    addImage: `${API}/api/${VERSION}/files/upload/`,
  },
};


export default endPoints;

También el env local es

TAILWIND_MODE=watch
NEXT_PUBLIC_API_URL=https://api.escuelajs.co
NEXT_PUBLIC_API_VERSION=v1

El reto de la clase a la fecha:

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endPoints = {
    auth: {
        login: `${API}/api/${VERSION}/auth/login`,
        profile: `${API}/api/${VERSION}/auth/profile`,
        refresh: `${API}/api/${VERSION}/auth/refresh-token`,
    },
    products: {
        getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
        putProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
        deleteProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
        getProducts: (limit = 5, offset = 0) => `${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,  
        postProducts: `${API}/api/${VERSION}/products`,         
    },
    users: {
        getUser: (id) => `${API}/api/${VERSION}/users/${id}`,
        putUser: (id) => `${API}/api/${VERSION}/users/${id}`,
        deleteUser: (id) => `${API}/api/${VERSION}/users/${id}`,
        getUsers: (limit = 5) => `${API}/api/${VERSION}/users?limit=${limit}`,
        postUsers: `${API}/api/${VERSION}/users`,
        available: `${API}/api/${VERSION}/users/is-available`,
    },
    categories: {
        getCategorie: (id) => `${API}/api/${VERSION}/categories/${id}`,
        putCategorie: (id) => `${API}/api/${VERSION}/categories/${id}`,
        deleteCategorie: (id) => `${API}/api/${VERSION}/categories/${id}`,
        getCategories: (limit = 5) => `${API}/api/${VERSION}/categories?limit=${limit}`, 
        postCategories: `${API}/api/${VERSION}/categories`,
        getCategoriesProducts: (id, limit = 5 , offset = 0) => `${API}/api/${VERSION}/categories/${id}/products?limit=${limit}&offset=${offset}`,  
    },
    files: {
        upload: `${API}/api/${VERSION}/files/upload`,
        getFile: (fileName) => `${API}/api/${VERSION}/files/${fileName}`,
    },
};

export default endPoints;

.env.local:

TAILWIND_MODE=watch
NEXT_PUBLIC_API_URL=https://api.escuelajs.co
NEXT_PUBLIC_API_VERSION=v1

src/services/api/index.js:

const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_VERSION;

const endPoints = {
    auth: {
        login: `${API}/api/${VERSION}/auth/login`,
        profile: `${API}/api/${VERSION}/auth/profile`,
    },
    products: {
        getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
        getAllProducts: () => `${API}/api/${VERSION}/products`
    },
    users: {
        users: `${API}/${VERSION}/users`,
        isAvailable: `${API}/${VERSION}/users/is-available`,
    },
    categories: {
        getCategorie: (id) => `${API}/${VERSION}/categories/${id}`,
        getAllCategories: ()=> `${API}/${VERSION}/categories`,
    },
    files: {
        uploadFile: (fileName)=> `${API}/${VERSION}/files/${fileName}`, 
        uploadFiles: ()=> `${API}/${VERSION}/files/upload`,
    }
}

export default endPoints

mi intento del reto:

const endPoints = {
  auth: {
    login: `${API}/api/${VERSION}/auth/login`,
    profile: `${API}/api/${VERSION}/auth/profile`,
  },
  products: {
    getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
    getListProducts: (limit, offset) => `${API}/api/${VERSION}/products?limit=${limit}&offset=${offset}`,
    postProducts: `${API}/api/${VERSION}/products`,
    putProducts: (id) => `${API}/api/${VERSION}/products/${id}`,
    deleteProducts: (id) => `${API}/api/${VERSION}/products/${id}`,
  },
  users: {
    getUsersList: (limit) => `${API}/api/${VERSION}/users?limit=${limit}`,
    postUser: `${API}/api/${VERSION}/users`,
  },
  categories: {
    getListCategories: `${API}/api/${VERSION}/categories?limit=5`,
    postCategory: `${API}/api/${VERSION}/categories/`,
    getCategory: (id) => `${API}/api/${VERSION}/categories/${id}`,
    putCategory: (id) => `${API}/api/${VERSION}/categories/${id}`,
    getProductCategory: (id) => `${API}/api/${VERSION}/categories/${id}/products`
  },
  files: {
    postfile: `${API}/api/${VERSION}/files/upload/`,
    getFile: (filename) => `${API}/api/${VERSION}/files/${filename}`,
  },
};

Esta clase me parece re importante por la forma en gestionar y segementar los endpoints desde el frontend

// admin the requests the endpoints
const API = process.env.NEXT_PUBLIC_API_URL;
const VERSION = process.env.NEXT_PUBLIC_API_URL_VERSION;

const endpoints = {
  auth: {
    login: `${API}/api/${VERSION}/auth/login`,
    profile: `${API}/api/${VERSION}/auth/profile`,
  },
  products: {
    getAllProducts: `${API}/api/${VERSION}/products`,
    getProduct: (id) => `${API}/api/${VERSION}/products/${id}`,
  },
  users: {
    getAllUsers: `${API}/api/${VERSION}/users`,
    userIsAvailable: `${API}/api/${VERSION}/users/is-available`,
  },
  categories: {
    getAllCategories: `${API}/api/${VERSION}/categories`,
    getCategory: (id) => `${API}/api/${VERSION}/categories/${id}`,
    getCategoryWithProduct: (id) => `${API}/api/${VERSION}/categories/${id}/products`,
  },
  files: {
    upload: `${API}/api/${VERSION}/files/upload`,
    getFile: (fileName) => `${API}/api/${VERSION}/files/${fileName}`,
  },
};

export default endpoints;