> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tktchurch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Signed URL

> Get a signed URL for accessing a file

<Note>
  This endpoint requires authentication and the `viewFiles` permission.
</Note>

### Path Parameters

<ParamField path="provider" type="string" required>
  The storage provider. One of:

  * `s3`: Amazon S3 storage
  * `local`: Local file storage
</ParamField>

<ParamField path="key" type="string" required>
  The storage key/path of the file
</ParamField>

### Query Parameters

<ParamField query="expires" type="integer" required={false}>
  Number of minutes until the signed URL expires (default: 60)
</ParamField>

### Response

Returns a string containing the signed URL that can be used to access the file.

### Error Responses

<ResponseField name="error" type="object">
  Error details when the request fails

  <Expandable title="Error Object">
    <ResponseField name="status" type="integer">
      HTTP status code
    </ResponseField>

    <ResponseField name="reason" type="string">
      Error message explaining why the request failed
    </ResponseField>
  </Expandable>
</ResponseField>

<Note>
  Common error cases:

  * 400 Bad Request: Invalid provider or key
  * 401 Unauthorized: Missing or invalid access token
  * 403 Forbidden: Missing required permission
  * 404 Not Found: File not found
</Note>

<RequestExample>
  ```bash cURL theme={null}
  curl -X GET "https://api.tktchurch.com/v1/files/provider/s3/signed-url/uploads/abc123.jpg?expires=30" \
    -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
  ```

  ```javascript JavaScript theme={null}
  const getSignedUrl = async (accessToken, provider, key, expiresInMinutes = 60) => {
    const response = await fetch(
      `https://api.tktchurch.com/v1/files/provider/${provider}/signed-url/${key}?expires=${expiresInMinutes}`,
      {
        headers: {
          'Authorization': `Bearer ${accessToken}`
        }
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.reason || 'Failed to get signed URL');
    }

    return response.text();
  };

  // Usage
  try {
    const signedUrl = await getSignedUrl(
      'eyJhbGciOiJIUzI1NiIs...',
      's3',
      'uploads/abc123.jpg',
      30
    );
    console.log('Signed URL:', signedUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
  ```

  ```swift Swift theme={null}
  func getSignedUrl(
      accessToken: String,
      provider: String,
      key: String,
      expiresInMinutes: Int = 60
  ) async throws -> String {
      var components = URLComponents(string: "https://api.tktchurch.com/v1/files/provider/\(provider)/signed-url/\(key)")!
      components.queryItems = [
          URLQueryItem(name: "expires", value: String(expiresInMinutes))
      ]
      
      var urlRequest = URLRequest(url: components.url!)
      urlRequest.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
      
      let (data, response) = try await URLSession.shared.data(for: urlRequest)
      
      guard let httpResponse = response as? HTTPURLResponse else {
          throw URLError(.badServerResponse)
      }
      
      if httpResponse.statusCode != 200 {
          throw URLError(.badServerResponse)
      }
      
      return String(decoding: data, as: UTF8.self)
  }

  // Usage
  do {
      let signedUrl = try await getSignedUrl(
          accessToken: "eyJhbGciOiJIUzI1NiIs...",
          provider: "s3",
          key: "uploads/abc123.jpg",
          expiresInMinutes: 30
      )
      print("Signed URL:", signedUrl)
  } catch {
      print("Error:", error)
  }
  ```

  ```kotlin Kotlin theme={null}
  suspend fun getSignedUrl(
      accessToken: String,
      provider: String,
      key: String,
      expiresInMinutes: Int = 60
  ): String {
      val url = buildString {
          append("https://api.tktchurch.com/v1/files/provider/$provider/signed-url/$key")
          append("?expires=$expiresInMinutes")
      }

      val request = Request.Builder()
          .url(url)
          .get()
          .header("Authorization", "Bearer $accessToken")
          .build()

      return withContext(Dispatchers.IO) {
          client.newCall(request).execute().use { response ->
              if (!response.isSuccessful) {
                  throw IOException("Unexpected response ${response.code}")
              }
              
              response.body?.string() ?: throw IOException("Empty response")
          }
      }
  }

  // Usage
  try {
      val signedUrl = getSignedUrl(
          "eyJhbGciOiJIUzI1NiIs...",
          "s3",
          "uploads/abc123.jpg",
          30
      )
      println("Signed URL: $signedUrl")
  } catch (e: Exception) {
      println("Error: ${e.message}")
  }
  ```

  ```typescript React Native theme={null}
  const getSignedUrl = async (
    accessToken: string,
    provider: 's3' | 'local',
    key: string,
    expiresInMinutes: number = 60
  ): Promise<string> => {
    try {
      const response = await axios.get<string>(
        `https://api.tktchurch.com/v1/files/provider/${provider}/signed-url/${key}`,
        {
          headers: {
            'Authorization': `Bearer ${accessToken}`
          },
          params: {
            expires: expiresInMinutes
          }
        }
      );
      return response.data;
    } catch (error) {
      if (axios.isAxiosError(error)) {
        throw new Error(error.response?.data?.reason || 'Failed to get signed URL');
      }
      throw error;
    }
  };

  // Usage
  try {
    const signedUrl = await getSignedUrl(
      'eyJhbGciOiJIUzI1NiIs...',
      's3',
      'uploads/abc123.jpg',
      30
    );
    console.log('Signed URL:', signedUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
  ```
</RequestExample>

<ResponseExample>
  ```text 200 Success theme={null}
  https://storage.example.com/uploads/abc123.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=...
  ```

  ```json 400 Bad Request theme={null}
  {
    "error": {
      "status": 400,
      "reason": "Invalid provider specified"
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "error": {
      "status": 401,
      "reason": "Invalid or expired access token"
    }
  }
  ```

  ```json 403 Forbidden theme={null}
  {
    "error": {
      "status": 403,
      "reason": "Missing required permission: viewFiles"
    }
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "error": {
      "status": 404,
      "reason": "File not found"
    }
  }
  ```
</ResponseExample>
