---
updatedAt: 2025-04-16T13:06:15.000Z
agentTools:
  projectIndex: https://docs.wistia.com/llms.txt
---

# Create Tag and Apply to Multiple Medias

```ruby Ruby
require 'net/http'
require 'json'
require 'uri'

BASE_URL = 'https://api.wistia.com/v1'
API_KEY = 'your-api-key'
TAG_NAME = 'test-tag'

def fetch_json_from_url(url, params = {}, method = 'Get', body_params = {})
  uri = URI(url)
  uri.query = URI.encode_www_form(params)
  req = Object.const_get("Net::HTTP::#{method.capitalize}").new(uri)
  req['Authorization'] = "Bearer #{API_KEY}"
  req['Content-Type'] = 'application/json'
  req['Accept'] = 'application/json'
  req.body = body_params.to_json if ['Post', 'Put'].include?(method.capitalize)

  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(req)
  end

  JSON.parse(res.body)
end

def create_tag
  fetch_json_from_url("#{BASE_URL}/tags", {}, 'Post', { name: TAG_NAME })
end

# medias param eg: [{ hashed_id: 'abc123', tags: ['tag-1', 'tag-2'] }]
def apply_tag_to_media(medias)
  medias.each do |m|
    id = m[:hashed_id]
    all_tags = Array(m[:tags]) + [TAG_NAME]
    resp = fetch_json_from_url("#{BASE_URL}/medias/#{id}.json", {}, 'Put', { tags: all_tags })
    if resp["tags"].any? { |tag| tag["name"] == TAG_NAME }
      puts "Successfully applied tag to media with id #{id}"
    else
      puts "Failed to apply tag to media with id #{id}. Response: #{resp}"
    end
    sleep(1) # Avoid hitting rate limit in example code
  end
end

def get_media_hashed_ids_and_tags_in_first_project
  project = fetch_json_from_url("#{BASE_URL}/projects").first
  medias = fetch_json_from_url("#{BASE_URL}/medias", { project_id: project['hashedId'] })
  medias.collect { |m| { hashed_id: m['hashed_id'], tags: m['tags'] }}
end

def create_tag_and_apply_to_all_media_in_first_project
  create_tag
  medias = get_media_hashed_ids_and_tags_in_first_project
  apply_tag_to_media(medias)
end

create_tag_and_apply_to_all_media_in_first_project
```

```javascript JavaScript
const axios = require('axios');

const BASE_URL = 'https://api.wistia.com/v1';
const API_KEY = 'your-api-key';
const TAG_NAME = 'test-tag';

async function fetchJsonFromUrl(url, params = {}, method = 'get', bodyParams = {}) {
  const options = {
    method: method,
    url: url,
    params: params,
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Accept': 'application/json'
    }
  };

  if (method.toLowerCase() !== 'get') {
    options.data = bodyParams;
  }

  try {
    const response = await axios(options);
    return response.data;
  } catch (error) {
    console.error(`Error in fetchJsonFromUrl: ${error}`);
    throw error;
  }
}

async function createTag() {
  try {
    return await fetchJsonFromUrl(`${BASE_URL}/tags`, {}, 'post', { name: TAG_NAME });
  } catch (error) {
    if (error.response && error.response.data && error.response.data.error === 'Validation failed: Name has already been taken') {
      console.log(`Tag with name "${TAG_NAME}" already exists.`);
      return null;
    } else {
      throw error;
    }
  }
}

async function fetchMedia(id) {
  try {
    const mediaResponse = await fetchJsonFromUrl(`${BASE_URL}/medias/${id}.json`);
    return mediaResponse;
  } catch (error) {
    console.error(`Failed to fetch media with id ${id}. Error: ${error}`);
    return null;
  }
}

async function applyTagToMedia(medias) {
  for (const m of medias) {
    const id = m.hashed_id;
    const mediaResponse = await fetchMedia(id);
    if (mediaResponse) {
      const tags = mediaResponse.tags.map(tag => tag.name) || [];
      tags.push(TAG_NAME);
      const resp = await fetchJsonFromUrl(`${BASE_URL}/medias/${id}.json`, {}, 'put', { tags: tags });
      if (resp.tags.some(tag => tag.name === TAG_NAME)) {
        console.log(`Successfully applied tag to media with id ${id}`);
      } else {
        console.log(`Failed to apply tag to media with id ${id}. Response: ${JSON.stringify(resp)}`);
      }
    }
    await new Promise(resolve => setTimeout(resolve, 500)); // Avoid hitting rate limit in example code
  }
}

async function getMediaHashedIdsInFirstProject() {
  const project = (await fetchJsonFromUrl(`${BASE_URL}/projects`))[0];
  const medias = await fetchJsonFromUrl(`${BASE_URL}/medias`, { project_id: project.hashedId });
  return medias.map(m => ({ hashed_id: m.hashed_id }));
}

async function createTagAndApplyToAllMediaInFirstProject() {
  try {
    await createTag();
    const medias = await getMediaHashedIdsInFirstProject();
    await applyTagToMedia(medias);
  } catch (error) {
    console.error(`Failed to create tag and apply to all media. Error: ${error}`);
  }
}

createTagAndApplyToAllMediaInFirstProject();
```

```json Response Example
{"success":true}
```

# Set API Bearer Token

<!-- ruby@6 -->
<!-- javascript@4 -->

Replace "your-api-key" with your api token. It can be found in your API Access tab in Account settings (/account/api)

# Create a new tag

<!-- ruby@7,25-27 -->
<!-- javascript@5,31-42 -->



# Get Media Hashed Ids and Tags for First Project

<!-- ruby@44-48,52 -->
<!-- javascript@72-76 -->

This gets all media hashed_ids and tags for the first project in the account.

Because updating tags will replace existing tags, we collect the existing tags as well as the hashed_id.

# Apply tags to medias

<!-- ruby@30-42,53,56 -->
<!-- javascript@54-70,82,88 -->

Looping through the medias, we merge the old and new tags, and then call the Media#update endpoint.