# Upsert branch

PUT https://app.launchdarkly.com/api/v2/code-refs/repositories/{repo}/branches/{branch}
Content-Type: application/json

Create a new branch if it doesn't exist, or update the branch if it already exists.

Reference: https://launchdarkly.com/docs/api/code-references/put-branch

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: LaunchDarkly REST API
  version: 1.0.0
paths:
  /api/v2/code-refs/repositories/{repo}/branches/{branch}:
    put:
      operationId: put-branch
      summary: Upsert branch
      description: >-
        Create a new branch if it doesn't exist, or update the branch if it
        already exists.
      tags:
        - subpackage_codeReferences
      parameters:
        - name: repo
          in: path
          description: The repository name
          required: true
          schema:
            type: string
            format: string
        - name: branch
          in: path
          description: The URL-encoded branch name
          required: true
          schema:
            type: string
            format: string
        - name: Authorization
          in: header
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Action succeeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Code references_putBranch_Response_200'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InvalidRequestErrorRep'
        '401':
          description: Invalid access token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UnauthorizedErrorRep'
        '403':
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ForbiddenErrorRep'
        '404':
          description: Invalid resource identifier
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NotFoundErrorRep'
        '409':
          description: Status conflict
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StatusConflictErrorRep'
        '429':
          description: Rate limited
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RateLimitedErrorRep'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/putBranch'
servers:
  - url: https://app.launchdarkly.com
  - url: https://app.launchdarkly.us
components:
  schemas:
    UnixMillis:
      type: integer
      format: int64
      title: UnixMillis
    HunkRep:
      type: object
      properties:
        startingLineNumber:
          type: integer
          description: Line number of beginning of code reference hunk
        lines:
          type: string
          description: Contextual lines of code that include the referenced feature flag
        projKey:
          type: string
          description: The project key
        flagKey:
          type: string
          description: The feature flag key
        aliases:
          type: array
          items:
            type: string
          description: An array of flag key aliases
      required:
        - startingLineNumber
      title: HunkRep
    ReferenceRep:
      type: object
      properties:
        path:
          type: string
          description: File path of the reference
        hint:
          type: string
          description: Programming language used in the file
        hunks:
          type: array
          items:
            $ref: '#/components/schemas/HunkRep'
      required:
        - path
        - hunks
      title: ReferenceRep
    putBranch:
      type: object
      properties:
        name:
          type: string
          description: The branch name
        head:
          type: string
          description: An ID representing the branch HEAD. For example, a commit SHA.
        updateSequenceId:
          type: integer
          format: int64
          description: >-
            An optional ID used to prevent older data from overwriting newer
            data. If no sequence ID is included, the newly submitted data will
            always be saved.
        syncTime:
          $ref: '#/components/schemas/UnixMillis'
          description: A timestamp indicating when the branch was last synced
        references:
          type: array
          items:
            $ref: '#/components/schemas/ReferenceRep'
          description: An array of flag references found on the branch
        commitTime:
          $ref: '#/components/schemas/UnixMillis'
          description: A timestamp of the current commit
      required:
        - name
        - head
        - syncTime
      title: putBranch
    Code references_putBranch_Response_200:
      type: object
      properties: {}
      description: Empty response body
      title: Code references_putBranch_Response_200
    InvalidRequestErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: InvalidRequestErrorRep
    UnauthorizedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: UnauthorizedErrorRep
    ForbiddenErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: ForbiddenErrorRep
    NotFoundErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: NotFoundErrorRep
    StatusConflictErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: StatusConflictErrorRep
    RateLimitedErrorRep:
      type: object
      properties:
        code:
          type: string
          description: Specific error code encountered
        message:
          type: string
          description: Description of the error
      required:
        - code
        - message
      title: RateLimitedErrorRep
  securitySchemes:
    ApiKey:
      type: apiKey
      in: header
      name: Authorization

```

## SDK Code Examples

```python
import requests

url = "https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch"

payload = {
    "name": "main",
    "head": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
    "syncTime": 1636558831870
}
headers = {
    "Authorization": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.put(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch';
const options = {
  method: 'PUT',
  headers: {Authorization: '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"name":"main","head":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","syncTime":1636558831870}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch"

	payload := strings.NewReader("{\n  \"name\": \"main\",\n  \"head\": \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\",\n  \"syncTime\": 1636558831870\n}")

	req, _ := http.NewRequest("PUT", url, payload)

	req.Header.Add("Authorization", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

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

url = URI("https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Put.new(url)
request["Authorization"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"main\",\n  \"head\": \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\",\n  \"syncTime\": 1636558831870\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.put("https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch")
  .header("Authorization", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"main\",\n  \"head\": \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\",\n  \"syncTime\": 1636558831870\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('PUT', 'https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch', [
  'body' => '{
  "name": "main",
  "head": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
  "syncTime": 1636558831870
}',
  'headers' => [
    'Authorization' => '<apiKey>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch");
var request = new RestRequest(Method.PUT);
request.AddHeader("Authorization", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"main\",\n  \"head\": \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\",\n  \"syncTime\": 1636558831870\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "main",
  "head": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
  "syncTime": 1636558831870
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://app.launchdarkly.com/api/v2/code-refs/repositories/repo/branches/branch")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PUT"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```