Sample image upload rest api for testing


In this post, we will provide a sample image upload REST API for testing purposes. Using this API, you can upload an image file, and in response, you will receive the image URL. 

Recently, I have been working on a project that requires uploading a user profile picture to a REST endpoint. 

I faced difficulties finding an open and free REST API for uploading images to test my code. That's why I decided to provide an endpoint so that other developers can use it for their testing. 

It doesn't matter if you are a front-end developer or a backend developer; it will work on all platforms such as JavaScript, React, Python, Java, C#, etc.

I have created an endpoint that accepts multipart/form-data in the request body. You can send your file inside the key 'ImageFile'.

If you need a sample API for testing purposes, you can try the API below.



Upload Imageapi/uploadfile/uploadimage
Url: https://www.quickpickdeal.com/api/uploadfile/uploadimage
Response body
{
                                "Success": true,
                                "Error": "Image uploaded successfully!",
                                "Data": "https://www.quickpickdeal.com/images/API.Png"
}
If no file is sent in the request body, an error message will be returned stating that you need to send an image file in the request body.
{
                                "Success": false,
                                "Error": "Please upload an image file!",
                                "Data": null
}
I have attached a screenshot of Postman to provide you with a visual guide on how to upload an image using the REST endpoint. Take a look to see the step-by-step process.

I have created the endpoint using ASP.NET Core API. If you are looking for the source code to create an API for uploading images in ASP.NET Core, you can refer to the code below:

 [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        private readonly IWebHostEnvironment _env;
        public UploadFileController(IWebHostEnvironment env)
        {
            _env = env;
        }
        // api/UploadFile/UploadImage
        [HttpPost]
        public async Task<IActionResult> UploadImage([FromForm] UploadImageDTO uploadImageDTO)
        {
            ResponseDTO responseDTO = new ResponseDTO();
            responseDTO.Success = false;
            try
            {
                if (uploadImageDTO.ImageFile != null && uploadImageDTO.ImageFile.Length > 0)
                {
                    var uploadpath = Path.Combine(_env.WebRootPath, "images");
                    string filename = uploadImageDTO.ImageFile.FileName;
                    using (var fileStream = new FileStream(Path.Combine(uploadpath, filename), FileMode.Create))
                    {
                        await uploadImageDTO.ImageFile.CopyToAsync(fileStream);
                    }
                    responseDTO.Success = true;
                    responseDTO.Error = "Image uploaded successfully!";
                    responseDTO.Data = $"{CommonVariable.BaseUrl}images/{filename}";
                }
                else
                {
                    responseDTO.Error = "Please upload an image file!";
                }
            }
            catch(Exception ex)
            {
                responseDTO.Error = ex.Message;
            }
            return Ok(responseDTO);
        }
    }
    public class UploadImageDTO
    {
        public IFormFile ImageFile { get; set; }
    }

Sample image upload rest api for testing python
Simple example of a REST API for image upload using Flask, a web framework for Python. 
Make sure to install Flask using pip install flask before running the code.

from flask import Flask, request, jsonify
import os

app = Flask(__name__)

# Set the upload folder
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/api/uploadFile/uploadImage', methods=['POST'])
def upload_file():
    # Check if the post request has the file part
    if 'ImageFile' not in request.files:
        return jsonify({'error': 'No file part'})

    file = request.files['ImageFile']

    # If the user does not select a file, the browser submits an empty file without a filename
    if file.filename == '':
        return jsonify({'error': 'No selected file'})

    # Save the file to the upload folder
    if file:
        filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filename)

        # Return the file URL in the response
        file_url = request.host_url + filename
        return jsonify({'file_url': file_url})

if __name__ == '__main__':
    app.run(debug=True)
Above using Flask app with an /api/UploadFile/UploadImage endpoint that accepts POST requests with a file attached in the ImageFile key of the multipart/form-data form. 

The uploaded file is then saved to the uploads folder, and the URL of the uploaded file is returned in the JSON response.

To test the endpoint, run the script, and use a tool like Postman to send a POST request with a file attached to the /api/UploadFile/UploadImage endpoint.

Sample image upload rest api for testing javascript

If you want to upload the image using javascript code then below is a simple example of a JavaScript code using the Fetch API to upload an image to a REST API endpoint. 
we have an API endpoint(/api/uploadFile/uploadImage) that accepts multipart/form-data.



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
</head>
<body>

    <input type="file" id="fileInput" />
    <button onclick="uploadImage()">Upload Image</button>

    <script>
        function uploadImage() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];

            if (!file) {
                alert('Please select a file');
                return;
            }

            const formData = new FormData();
            formData.append('ImageFile', file);

            fetch('/api/UploadFile/UploadImage', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('File uploaded successfully. Image URL:', data.file_url);
            })
            .catch(error => {
                console.error('Error uploading file:', error);
            });
        }
    </script>

</body>
</html>
Above script includes a simple HTML form with a file input and a button to trigger the image upload. The uploadImage function is called when the button is clicked, and it uses the Fetch API to send a POST request with the selected image file to the specified API endpoint.