Uploading files


Apollo Kotlin supports file uploads via the GraphQL multipart request specification with a few caveats:

  • Uploading files with GraphQL is most often suitable for proof-of-concept applications. In production, using purpose-built tools for file uploads may be preferable. Refer to this blog post for possible approaches and their advantages and disadvantages.

    • Neither the Apollo Router Core nor GraphOS Router support multipart/form-data uploads.

Uploading files with Apollo Kotlin

First, add the following custom scalar mapping to the Apollo Gradle plugin configuration:

Kotlin
build.gradle[.kts]
1apollo {
2  service("service") {
3    mapScalarToUpload("Upload")
4  }
5}

In this example, the GraphQL schema defines a custom scalar type named Upload. You can use a different name as needed for your schema.

 note
You don't need to register a type adapter for Upload, because the mapScalarToUpload method registers it automatically.

Now let's consider a mutation that takes an Upload as a parameter:

GraphQL
1mutation SingleUpload($file: Upload!) {
2  singleUpload(file: $file) {
3    id
4    path
5    filename
6    mimetype
7  }
8}

Create an instance of Upload using one of the factory methods:

Kotlin
1// If you're on Android/JVM, you can turn a File into an upload
2val upload = File.toUpload("application/json")
3
4// On multiplatform, you can use `DefaultUpload`
5val upload = DefaultUpload.Builder()
6              .fileName("filename.txt")
7              .content { sink ->
8                okioSource.use { sink.writeAll(it) }
9              }
10              .build()

And execute your mutation:

Kotlin
1val response = apolloClient.mutation(SingleUploadMutation(file = upload)).execute()