Skip to content

URL Shortener built with Python, Django Rest Framework. A simple and efficient API to create and manage short links.

Notifications You must be signed in to change notification settings

YarielZC/ylink-drf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

English | Español

ylink-drf: URL Shortener API

This is the source code for a RESTful API to shorten URLs, built with Python and Django REST Framework. It allows users to register, authenticate, and manage their own shortened links with advanced options.

Features

  • User authentication: Registration and login system based on authentication tokens.
  • URL shortening: Users can submit a long URL to receive a unique, short version.
  • Click limit: A maximum number of redirections can be set for each shortened link (max_touch_count).
  • Click tracking: Counter for the number of times a shortened link has been accessed.
  • Custom metadata: Add a label and a description to your links for better organization.
  • Redirection: The root path redirects to the original URL corresponding to the provided short code.

Technologies Used

  • Python
  • Django
  • Django REST Framework

Installation

  1. Clone the repository:

    git clone https://github.com/YarielZC/ylink-drf.git
    cd ylink-drf
  2. Create and activate a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows use `venv\Scripts\activate`
  3. Install dependencies:

    pip install -r requirements.txt
  4. Run database migrations:

    python manage.py migrate
  5. Create a superuser (optional, for the admin panel):

    python manage.py createsuperuser
  6. Start the development server:

    python manage.py runserver

    The API will be available at http://127.0.0.1:8000/.

API Endpoints

The available API endpoints are detailed below:

Authentication

  • POST /login/: Authenticates a user and returns an authentication token.

    Request Body:

    {
        "username": "your_username",
        "password": "your_password"
    }

Users

  • POST /user/: Registers a new user.

    Request Body:

    {
        "username": "new_user",
        "email": "user@example.com",
        "password": "a_secure_password",
        "confirm_password": "a_secure_password"
    }

Links

  • GET /api/v1/links/: Gets the list of shortened links for the authenticated user.

  • POST /api/v1/links/: Creates a new shortened link.

    Parameters:

    • redirect_url (Required): The original URL to redirect to.
    • max_touch_count (Optional): The maximum number of times the link can be accessed.
    • label (Optional): A short label to identify the link.
    • description (Optional): A more detailed description of the link.
  • GET /api/v1/links/<id>/: Gets the details of a specific shortened link.

  • PUT /api/v1/links/<id>/: Updates a shortened link.

  • DELETE /api/v1/links/<id>/: Deletes a shortened link.

Redirection

  • GET /<short>: Redirects to the redirect_url associated with the short code (short).

Usage

  1. Register a new user by sending a POST request to /user/ with the required data.

  2. Get your authentication token by sending a POST request to /login/ with your credentials.

  3. To create a shortened link, send a POST request to /api/v1/links/ including the token in the Authorization header.

    Example Authorization header:

    Authorization: Token YOUR_AUTH_TOKEN
    

    Example request body:

    {
        "redirect_url": "https://www.a-very-long-example-url.com/this/is/a/long/path",
        "label": "My Test Link",
        "description": "This is a link for the README documentation",
        "max_touch_count": 100
    }
  4. The response will provide you with the shortened URL and the details of the created link.

  5. You can view the statistics for your links by making a GET request to /api/v1/links/.

Contributing

Contributions are welcome. Please open an issue to discuss any changes you would like to make.


English | Español

ylink-drf: Acortador de Enlaces API

Este es el código fuente de una API RESTful para acortar enlaces construida con Python y Django REST Framework. Permite a los usuarios registrarse, autenticarse y gestionar sus propios enlaces acortados con opciones avanzadas.

Características

  • Autenticación de usuarios: Sistema de registro e inicio de sesión basado en tokens de autenticación.
  • Acortamiento de enlaces: Los usuarios pueden enviar una URL larga para recibir una versión corta y única.
  • Límite de clics: Se puede establecer un número máximo de redirecciones para cada enlace acortado (max_touch_count).
  • Seguimiento de clics: Contador de la cantidad de veces que se ha accedido a un enlace acortado.
  • Metadatos personalizados: Agrega una etiqueta (label) y una descripción (description) a tus enlaces para una mejor organización.
  • Redirección: La ruta principal redirige a la URL original correspondiente al enlace corto proporcionado.

Tecnologías Utilizadas

  • Python
  • Django
  • Django REST Framework

Instalación

  1. Clona el repositorio:

    git clone https://github.com/YarielZC/ylink-drf.git
    cd ylink-drf
  2. Crea y activa un entorno virtual:

    python -m venv venv
    source venv/bin/activate  # En Windows usa `venv\Scripts\activate`
  3. Instala las dependencias:

    pip install -r requirements.txt
  4. Realiza las migraciones de la base de datos:

    python manage.py migrate
  5. Crea un superusuario (opcional, para el panel de administración):

    python manage.py createsuperuser
  6. Inicia el servidor de desarrollo:

    python manage.py runserver

    La API estará disponible en http://127.0.0.1:8000/.

Endpoints de la API

A continuación se detallan los endpoints disponibles en la API:

Autenticación

  • POST /login/: Autentica a un usuario y devuelve un token de autenticación.

    Cuerpo de la petición:

    {
        "username": "tu_usuario",
        "password": "tu_contraseña"
    }

Usuarios

  • POST /user/: Registra un nuevo usuario.

    Cuerpo de la petición:

    {
        "username": "nuevo_usuario",
        "email": "usuario@ejemplo.com",
        "password": "una_contraseña_segura",
        "confirm_password": "una_contraseña_segura"
    }

Enlaces

  • GET /api/v1/links/: Obtiene la lista de enlaces acortados por el usuario autenticado.

  • POST /api/v1/links/: Crea un nuevo enlace acortado.

    Parámetros:

    • redirect_url (Requerido): La URL original a la que se va a redirigir.
    • max_touch_count (Opcional): El número máximo de veces que se puede acceder al enlace.
    • label (Opcional): Una etiqueta corta para identificar el enlace.
    • description (Opcional): Una descripción más detallada del enlace.
  • GET /api/v1/links/<id>/: Obtiene los detalles de un enlace acortado específico.

  • PUT /api/v1/links/<id>/: Actualiza un enlace acortado.

  • DELETE /api/v1/links/<id>/: Elimina un enlace acortado.

Redirección

  • GET /<short>: Redirige al redirect_url asociado con el código corto (short).

Uso

  1. Registra un nuevo usuario enviando una petición POST a /user/ con los datos requeridos.

  2. Obtén tu token de autenticación enviando una petición POST a /login/ con tus credenciales.

  3. Para crear un enlace acortado, envía una petición POST a /api/v1/links/ incluyendo el token en la cabecera de autorización.

    Ejemplo de cabecera de autorización:

    Authorization: Token TU_TOKEN_DE_AUTENTICACION
    

    Ejemplo de cuerpo de la petición:

    {
        "redirect_url": "https://www.ejemplolargo.com/esto/es/un/enlace/muy/largo",
        "label": "Mi Enlace de Prueba",
        "description": "Este es un enlace para la documentación del README",
        "max_touch_count": 100
    }
  4. La respuesta te proporcionará la URL acortada y los detalles del enlace creado.

  5. Puedes ver las estadísticas de tus enlaces haciendo una petición GET a /api/v1/links/.

Contribuciones

Las contribuciones son bienvenidas. Por favor, abre un "issue" para discutir los cambios que te gustaría hacer.

About

URL Shortener built with Python, Django Rest Framework. A simple and efficient API to create and manage short links.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages