GraphQL Multipart Request: What It Is and How It Works
GraphQL multipart request is a way to send files along with GraphQL operations using the multipart/form-data format. It allows clients to upload files in the same request as queries or mutations by splitting the request into parts. This is essential because GraphQL itself does not natively support file uploads.How It Works
A GraphQL multipart request works by packaging the GraphQL operation and files into a single HTTP request using the multipart/form-data format. Imagine sending a letter with several envelopes inside: one envelope contains the GraphQL query or mutation, and the others contain the files you want to upload.
The request includes a special operations part with the GraphQL query and variables, and a map part that tells the server which files correspond to which variables. The server then processes the request, extracts the files, and links them to the right places in the GraphQL operation.
This method solves the problem that GraphQL queries are usually sent as JSON, which cannot carry files directly. Using multipart requests lets you combine file uploads and GraphQL operations seamlessly in one go.
Example
This example shows a simple GraphQL mutation to upload a file using a multipart request format.
POST /graphql HTTP/1.1 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="operations" {"query":"mutation ($file: Upload!) { uploadFile(file: $file) { filename mimetype } }","variables":{"file":null}} ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="map" {"0":["variables.file"]} ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="0"; filename="example.txt" Content-Type: text/plain Hello, this is the content of the file. ------WebKitFormBoundary7MA4YWxkTrZu0gW--
When to Use
Use GraphQL multipart requests when your API needs to handle file uploads alongside GraphQL queries or mutations. This is common in applications where users upload images, documents, or other files while interacting with data.
For example, social media apps let users upload profile pictures or posts with images. E-commerce platforms allow uploading product photos. Using multipart requests keeps the upload process efficient and integrated with your GraphQL API.
Without this approach, you would need separate endpoints for file uploads, complicating client-server communication.
Key Points
- GraphQL multipart requests use
multipart/form-datato send files and operations together. - The request includes
operationsandmapparts to link files to variables. - This method enables file uploads in GraphQL, which does not support files natively.
- It simplifies client-server communication by combining uploads with queries or mutations.