# Create a file

`POST /files`

> This is a subset of the full specification, limited to the `POST /files` operation.
>
> You can find the full specification here: /_bundle/docs/dev-docs/api/index.yaml

```yaml
openapi: 3.1.1
info:
  version: latest
  title: Core APIs
  contact:
    name: Rebilly API Support
    url: https://www.rebilly.com/contact/
    email: integrations@rebilly.com
  license:
    name: Rebilly
    url: https://www.rebilly.com/api-license/
  termsOfService: https://www.rebilly.com/terms-of-use/
  x-logo:
    url: https://rebilly-core.redoc.ly/rb_apiLogo.svg
    backgroundColor: '#0044d4'
  description: This is a subset of the full specification, limited to the `POST /files` operation.
  x-metadata:
    description: The most common APIs used to automate common workflows.
    redocly_category: API Reference
servers:
  - url: https://api-sandbox.rebilly.com/organizations/{organizationId}
    description: Sandbox server
    variables:
      organizationId:
        default: '{organizationId}'
        description: |-
          Unique organization identifier.
          An organization is an entity that represents a company.
          For more information, see [Obtain an organization ID](https://www.rebilly.com/docs/settings/organizations-and-websites/#obtain-your-organization-id-and-website-id).
  - url: https://api.rebilly.com/organizations/{organizationId}
    description: Live server
    variables:
      organizationId:
        default: '{organizationId}'
        description: |-
          Unique organization identifier.
          An organization is an entity that represents a company.
          For more information, see [Obtain an organization ID](https://www.rebilly.com/docs/settings/organizations-and-websites/#obtain-your-organization-id-and-website-id).
security:
  - SecretApiKey: []
  - JWT: []
tags:
  - name: Files
    description: |-
      Use the file entity to store files and related metadata.
      Files can be sorted by size, MIME-type, user-defined tags, and description.

      The following methods are available to upload files:
      multipart/form-data encoded form, RAW POST &mdash;
      by sending the file contents as the POST body, and fetching from URL &mdash;
      by providing the file URL using the 'url' parameter.

      Use the attachments entity to link a file to one or multiple objects, such as:
      customer, dispute, transaction, order, plan, product, invoice, or timeline comment.
      Use attachments to quickly find and use files related to specific entities.
x-tagGroups:
  - name: Misc
    tags:
      - Files
paths:
  /files:
    post:
      x-products:
        - Core
      tags:
        - Files
      summary: Create a file
      operationId: PostFile
      x-sdk-operation-name: upload
      security:
        - SecretApiKey: []
        - JWT: []
        - PublishableApiKey: []
      description: |-
        Creates a file.

        Additionally, a file can be sent by:

         - Multipart/form-data POST request: In this request,
         the file is uploaded and all property names are the same as the JSON names.
         - File body request: In this request,
         the file body is sent as the request body, with the appropriate `Content-Type`.
         No additional properties can be set with the request data.

        Permitted file types: `.jpg`, `.png`, `.gif`, `.webp`, `.svg`, and `.pdf`.
        Scripts, event handlers, and references to external files are removed from an SVG file before it is stored.

        When using a publishable API key or the JSON Web Token (JWT) of a customer, only private files can be created.
        The files can be modified at a later point or time,
        or can be accessed using a secret API key.
        When using a publishable API key or the JWT of a customer, a file cannot be created from a URL.
      requestBody:
        content:
          application/json:
            schema:
              oneOf:
                - $ref: '#/components/schemas/FileCreateFromInline'
                - $ref: '#/components/schemas/FileCreateFromUrl'
        required: true
      responses:
        '201':
          description: File created.
          headers:
            Location:
              $ref: '#/components/headers/Location'
            Rate-Limit-Limit:
              $ref: '#/components/headers/Rate-Limit-Limit'
            Rate-Limit-Remaining:
              $ref: '#/components/headers/Rate-Limit-Remaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/File'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/ValidationError'
        '429':
          $ref: '#/components/responses/TooManyRequests'
      x-codeSamples:
        - lang: PHP
          label: PHP-SDK-2.0
          source: |
            $fileForm = new Rebilly\Entities\File();
            $fileForm->setUrl('http://test.com/somefile.jpg');

            try {
                $file = $client->files()->create($fileForm);
            } catch (Rebilly\Http\Exception\DataValidationException $e) {
                print_r($e->getValidationErrors());
            }
        - lang: JavaScript
          source: |
            // using a FileList to fetch a file
            const fileObject = fileList[0];

            const addedFile = await api.files.upload({fileObject});




            // or, upload and update a file at the same time

            // define file data
            const data = {
                description: 'my new file',
                tags: ['original']
            };

            const updatedFile = await api.files.uploadAndUpdate({fileObject, data});
        - lang: PHP
          source: |-
            $service = new \Rebilly\Sdk\Service($client);

            $fileForm = new \Rebilly\Sdk\Model\FileCreateFromUrl();
            $fileForm->setUrl('http://test.com/somefile.jpg');

            try {
                $file = $service->files()->upload($fileForm);
            } catch (\Rebilly\Sdk\Exception\DataValidationException $e) {
                print_r($e->getValidationErrors());
            }
components:
  securitySchemes:
    JWT:
      description: |-
        JWT is a short lifetime token that can be assigned a specific expiration time.

        Usage format: `Bearer <JWT>`.
      type: http
      scheme: bearer
      bearerFormat: JWT
    PublishableApiKey:
      description: |-
        This authentication method is applicable to specific operations.

        To create a publishable API key, see [Create an API key](https://www.rebilly.com/catalog/all/api-keys/postapikey).
      name: Authorization
      type: apiKey
      in: header
    SecretApiKey:
      description: |-
        Never share your secret keys.
        Keep them guarded and secure.

        Use your secret API key only to make requests from the server side.
        To authenticate, provide your secret key in the request header.
      name: REB-APIKEY
      type: apiKey
      in: header
  headers:
    Location:
      description: Location of the related resource.
      schema:
        type: string
        format: uri
      example: https://api.rebilly.com/example
    Rate-Limit-Limit:
      description: |-
        Maximum number of requests available at one time for this rate limit.
        For more information, see [Rate limits](#section/Rate-limits).
      schema:
        type: integer
      example: 500
    Rate-Limit-Remaining:
      description: |-
        Number of requests still available for this rate limit.
        For more information, see [Rate limits](#section/Rate-limits).
      schema:
        type: integer
      example: 499
    Rate-Limit-Retry-After:
      description: Number of seconds to wait before retrying the request.
      schema:
        type: integer
      example: 1
  schemas:
    CreatedTime:
      type: string
      description: |-
        Date and time when the resource is created.
        This value is set automatically when the resource is created.
      format: date-time
      readOnly: true
      x-sortable: true
      x-label: Creation Time
    UpdatedTime:
      type: string
      description: |-
        Date and time when the resource is updated.
        This value is set automatically when the resource is updated.
      format: date-time
      readOnly: true
      x-sortable: true
      x-label: Last Update Time
    BaseProblem:
      type: object
      additionalProperties: true
      minProperties: 1
      description: RFC-7807 [problem details](https://tools.ietf.org/html/rfc7807) JSON object.
      properties:
        type:
          type: string
          description: |-
            Problem type in the form of a [URI](https://tools.ietf.org/html/rfc3986) reference.
            It should provide human-readable documentation for the problem type.
            When this member is not present, its value is assumed to be "about:blank".
          format: uri
        title:
          type: string
          description: |-
            Short, human-readable summary of the problem type.
            Other than for the purposes of localization, this should not change from occurrence to occurrence of the problem.
        detail:
          type: string
          description: Human-readable explanation that is specific to this occurrence of the problem.
        instance:
          type: string
          description: |-
            URI reference that identifies the specific occurrence of the problem.
            It may or may not yield further information if dereferenced.
    Unauthorized:
      allOf:
        - title: Unauthorized
        - type: object
          properties:
            status:
              type: integer
              description: HTTP status code.
              minimum: 401
              maximum: 401
        - $ref: '#/components/schemas/BaseProblem'
    OrganizationId:
      type: string
      description: |-
        Unique organization identifier.
        An organization is an entity that represents a company.
        For more information, see [Obtain an organization ID](https://www.rebilly.com/docs/settings/organizations-and-websites/#obtain-your-organization-id-and-website-id).
      maxLength: 50
      example: org_0YVDM8RC7GDADADSBSMW124JA8
    Forbidden:
      allOf:
        - title: Forbidden
        - type: object
          properties:
            status:
              type: integer
              description: HTTP status code.
              minimum: 403
              maximum: 403
            error:
              type: string
              description: |-
                Message that describes why the request is forbidden.
                Most responses use a descriptive message, such as `Not allowed to change security settings`.
                If the organization requires multi-factor authentication (MFA) and MFA verification has not been completed for the session, this value is `mfa_required`.
                If MFA verification has not been completed for the session and the operation requires a confirmed session, this value is `mfa_required_for_caller`.
                This includes turning on `requireMfa` and resetting MFA for a user.
                If the organization restricts access to a list of IP addresses and the request comes from an IP address that is not in the list, this value is `ip_not_allowed`.
            organizationId:
              description: |-
                ID of the organization that requires MFA or does not allow the IP address of the request.
                This property is present only if `error` is `mfa_required` or `ip_not_allowed`.
                The organization is the organization of the request or another organization that the request acts on.
              $ref: '#/components/schemas/OrganizationId'
        - $ref: '#/components/schemas/BaseProblem'
    InvalidFields:
      type: array
      description: Invalid field details.
      items:
        type: object
        properties:
          field:
            type: string
            description: |-
              Name of the field.
              Dot notation is used for nested object field names.
          message:
            description: Message field.
            type: string
      example:
        - field: field1
          message: field1 is invalid
        - field: subObject.field2
          message: field2 is invalid
        - field: subObject.field2
          message: another error in the field2
    ValidationError:
      allOf:
        - title: Validation error
        - type: object
          properties:
            status:
              type: integer
              description: HTTP status code.
              minimum: 422
              maximum: 422
        - $ref: '#/components/schemas/BaseProblem'
        - type: object
          properties:
            invalidFields:
              $ref: '#/components/schemas/InvalidFields'
    TooManyRequests:
      type: object
      additionalProperties: true
      minProperties: 1
      description: RFC-7807 [problem details](https://tools.ietf.org/html/rfc7807) JSON object.
      properties:
        type:
          type: string
          description: |-
            Problem type in the form of a [URI](https://tools.ietf.org/html/rfc3986) reference.
            It should provide human-readable documentation for the problem type.
            When this member is not present, its value is assumed to be "about:blank".
          format: uri
          example: about:blank
        title:
          type: string
          description: |-
            Short, human-readable summary of the problem type.
            Other than for the purposes of localization, this should not change from occurrence to occurrence of the problem.
          example: Rate Limit Exceeded
        status:
          type: integer
          description: HTTP status code.
          minimum: 429
          maximum: 429
        detail:
          type: string
          description: Human-readable explanation that is specific to this occurrence of the problem.
          example: A request cannot be executed because the user has sent too many requests within a certain period of time
        instance:
          type: string
          description: |-
            URI reference that identifies the specific occurrence of the problem.
            It may or may not yield further information if dereferenced.
    File:
      type: object
      properties:
        id:
          type: string
          description: ID of the file.
          readOnly: true
          maxLength: 50
          example: file_0YV7HZ7KDCC5WBV9Q7WRKG1H6N
        name:
          description: Original file name.
          type: string
          maxLength: 255
        extension:
          description: File extension.
          type: string
        description:
          description: Description of the file.
          type: string
          maxLength: 255
        sourceType:
          description: Source of the file.
          type:
            - string
            - 'null'
          enum:
            - upload
            - camera
            - organization-export
            - organization-closure-export
            - null
          example: upload
        tags:
          description: List of tags associated with the file.
          type: array
          items:
            type: string
        mime:
          description: MIME type of the file.
          type: string
          readOnly: true
          enum:
            - image/png
            - image/jpeg
            - image/gif
            - image/webp
            - image/svg+xml
            - application/pdf
            - application/json
            - application/zip
            - text/csv
        size:
          description: File size, in bytes.
          type: integer
          readOnly: true
        width:
          description: |-
            Width of the image.
            This field is applicable to images only.
          type:
            - integer
            - 'null'
          readOnly: true
        height:
          description: |-
            Height of the image.
            This field is applicable to images only.
          type:
            - integer
            - 'null'
          readOnly: true
        sha1:
          description: Hash sum of the file.
          type: string
          readOnly: true
        exifData:
          description: |-
            Collection of EXIF tags contained in the image metadata.
            This field is applicable to images only.
          type:
            - object
            - 'null'
          readOnly: true
          example:
            FileSize: 120
            Software: GIMP 2.4.5
        createdTime:
          $ref: '#/components/schemas/CreatedTime'
        updatedTime:
          $ref: '#/components/schemas/UpdatedTime'
        isPublic:
          description: |-
            Specifies if the file is available publicly without authentication.
            If this value is `true`, the `permalink` and `cdn` links in the `_links` section contain the public URLs.
            The `cdn` link is served from a cache and accepts the `imageSize` query parameter for images.
            If the organization has a verified media domain with no verification failure, the `cdn` link uses that domain.
            For more information, see [Configure a custom domain](https://www.rebilly.com/docs/settings/organizations-and-websites/#configure-a-custom-domain).
          type: boolean
        _links:
          type: array
          description: Related links.
          readOnly: true
          items:
            type: object
            properties:
              href:
                description: Link URL.
                type: string
              rel:
                description: Type of link.
                type: string
                enum:
                  - self
                  - download
                  - signedLink
                  - permalink
                  - cdn
    FileCreateFromInline:
      type: object
      required:
        - file
      properties:
        file:
          description: File in base64 encoded format.
          type: string
          example: R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=
        isPublic:
          description: |-
            Specifies if the file is available publicly without authentication.
            If this value is `true`, the `permalink` and `cdn` links in the `_links` section contain the public URLs.
            The `cdn` link is served from a cache and accepts the `imageSize` query parameter for images.
            If the organization has a verified media domain with no verification failure, the `cdn` link uses that domain.
            For more information, see [Configure a custom domain](https://www.rebilly.com/docs/settings/organizations-and-websites/#configure-a-custom-domain).
          type: boolean
          example: false
        name:
          description: File name used for downloading.
          type: string
          maxLength: 255
          example: logo.png
        description:
          description: Description of the file.
          type: string
          maxLength: 255
          example: My file description
        sourceType:
          description: Source of the file.
          type:
            - string
            - 'null'
          enum:
            - upload
            - camera
            - organization-export
            - organization-closure-export
            - null
          example: upload
        tags:
          description: List of tags associated with the file.
          type: array
          items:
            type: string
          example:
            - test
            - tags
    FileCreateFromUrl:
      type: object
      required:
        - url
      properties:
        url:
          description: URL of the file to upload.
          type: string
          example: https://app.rebilly.com/static/gateways/Stripe.png
        isPublic:
          description: |-
            Specifies if the file is available publicly without authentication.
            If this value is `true`, the `permalink` and `cdn` links in the `_links` section contain the public URLs.
            The `cdn` link is served from a cache and accepts the `imageSize` query parameter for images.
            If the organization has a verified media domain with no verification failure, the `cdn` link uses that domain.
            For more information, see [Configure a custom domain](https://www.rebilly.com/docs/settings/organizations-and-websites/#configure-a-custom-domain).
          type: boolean
          example: false
        name:
          description: File name used for downloading.
          type: string
          maxLength: 255
          example: logo.png
        description:
          description: Description of the file.
          type: string
          maxLength: 255
          example: My file description
        sourceType:
          description: Source of the file.
          type:
            - string
            - 'null'
          enum:
            - upload
            - camera
            - organization-export
            - organization-closure-export
            - null
          example: upload
        tags:
          description: List of tags associated with the file.
          type: array
          items:
            type: string
          example:
            - test
            - tags
  responses:
    Unauthorized:
      description: |-
        Unauthorized access.
        Invalid credentials used.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Unauthorized'
    Forbidden:
      description: |-
        Access forbidden.
        If the organization requires multi-factor authentication (MFA) and the session has not passed MFA, `error` is `mfa_required`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Forbidden'
    ValidationError:
      description: Invalid data sent.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ValidationError'
    TooManyRequests:
      description: Request rate limit exceeded.
      headers:
        Rate-Limit-Limit:
          $ref: '#/components/headers/Rate-Limit-Limit'
        Rate-Limit-Remaining:
          description: |-
            Number of requests still available for this rate limit.
            For more information, see [Rate limits](#section/Rate-limits).
          schema:
            type: integer
          example: 0
        Rate-Limit-Retry-After:
          $ref: '#/components/headers/Rate-Limit-Retry-After'
        Retry-After:
          description: Number of seconds to wait before retrying the request.
          schema:
            type: integer
          example: 1
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/TooManyRequests'
```
