# Add a user to a group via API?

**URL:** <https://meta.discourse.org/t/add-a-user-to-a-group-via-api/45077>\
**Category:** Development\
**Tags:** rest-api\
**Created:** [June 1, 2016, 9:42am UTC](https://meta.discourse.org/t/add-a-user-to-a-group-via-api/45077 "2016-06-01T09:42:55Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![DeanMarkTaylor](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/deanmarktaylor/32/102462_2.png) [@DeanMarkTaylor](https://meta.discourse.org/u/DeanMarkTaylor)\
**Post date:** [June 1, 2016, 11:25am UTC](https://meta.discourse.org/t/add-a-user-to-a-group-via-api/45077/2 "2016-06-01T11:25:25Z")

</div>

Something similar to this will add users “`bill`” and “`ben`” to group “`flower_pot_men`”:

```php
	/**
	 * Add users to a specified group, create the group if it doesn't exist.
	 *
	 * @param string $group_name name of group
	 * @param array $usernames users to add to group
	 *
	 * @return mixed HTTP return code and API return object
	 */

	public function add_users_to_group( $group_name, $usernames = array() ) {
		$group_id = null;

		$result = $this->get_request( "/admin/groups.json" );
		if ( $result->http_code != 200 ) {
			return $result;
		}

		foreach ( $result->result as $group ) {
			if ( $group->name === $group_name ) {
				$group_id = $group->id;
				break;
			}
			$group_id = false;
		}

		if ( ! $group_id ) {
			$result = $this->post_request( '/admin/groups', array( 'name' => $group_name ) );
			if ( $result->http_code != 200 ) {
				return $result;
			}
			$group_id = $result->result->basic_group->id;
		}
		if ( ! empty( $usernames ) ) {
			$params = array(
				'usernames' => implode( ',', $usernames )
			);
			$result = $this->put_request( '/admin/groups/' . $group_id . '/members.json', $params );
		}

		return $result;
	}

```

```PHP
$group_name = 'flower_pot_men';
$usernames = array( 'bill', 'ben' );
$result = $api->add_users_to_group( $group_name, $usernames );
if ( $result->http_code != 200 ) {
	// @todo handle the error
}

```

EDIT: The key point here is the `/admin` part is different from yours.  
EDIT #2: Updated to correctly reflect ID usage.

> **More about Bill and Ben**
>
> [![](https://global.discourse-cdn.com/meta/original/4X/a/9/3/a9391477d19da50d92816649777bbe0a53772af8.jpeg "ATV - "Bill & Ben The Flower Pot Men"") ](https://www.youtube.com/watch?v=hcF9JSxkUSE&t=2m4s)
> 
> “Wubb-ooooh”

---

_[View the full topic](https://meta.discourse.org/t/add-a-user-to-a-group-via-api/45077)._
