Upload Files in Swagger UI OpenAPI ASP.NET Core
Today in this article, we shall show to add swagger and Upload Files in Swagger UI using OpenAPI Specification V3.0.
Swagger or Open API specification provides the advantage of understanding the REST services easily (especially if developers are consuming any new API ) plus helps provide easy documentation and details of capabilities given Service/API owns.
We shall see the approach of both using IFormFile inbuilt support for Upload and we will also see how to handle the Upload using the IOperationFilter interface as well.
In OpenAPI 3.0 specification, files are defined as binary and files uploaded directly with the requested content.
OpenAPI JSON schema – Image file
Below is OpenAPI V3.0 JSON schema definition for the image file,
requestBody:
content:
image/png:
schema:
type: string
format: binary
Please note that if you are using IFormFile Interface in the API for sending a file sent with the HttpRequest, then it is pretty straightforward to get support for the swagger upload file in Swagger UI.
In fact, you don’t need to write a single line of code. once you enable Swagger using basic steps.
I recommend you to visit the below article, which describes how to enable swagger in basic 2-3 steps,
Uploading Single File in Swagger UI
We shall see how to upload a Single File in Swagger UI,
[HttpPost]
public Task UploadFile(IFormFile file)
{
return Task.CompletedTask;
}
Let’s see the generated Swagger definition,
Above once you choose a file or image for file upload, you shall be set to use for the given Routes/API.
You can use swagger to send files or post files as required.
Upload Multiple Files in Swagger UI
Users can Upload Multiple Files in Swagger UI using any of the below approaches.
Upload two files,
[HttpPost]
public Task UploadFiles(IFormFile file1, IFormFile file2)
{
return Task.CompletedTask;
}
Upload more than two files,
Using List<IFormFile>, one can load multiple files as well.
[HttpPost]
public Task UploadFileMulti(List<IFormFile> files)
{
return Task.CompletedTask;
}
OpenAPI JSON schema – Multipart Media file
If uploading other files, swagger UI uses represents it as a multipart media type.
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
orderId:
type: integer
userId:
type: integer
fileName:
type: string
format: binary
References :
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.