mockfly logo
Articles

>

How to Mock an API to Return a PDF or CSV

How to Mock an API to Return a PDF or CSV

Sometimes, requirements call for our API to return a PDF, CSV, xlsx, or any type of file depending on the functionality. Naturally, we also want our mock API to simulate this behavior as closely as possible. That is, we want our mock server to return a file instead of JSON or XML.

To demonstrate how to do this, we'll create an endpoint that simulates a server's API and instructs it to return a CSV. Then, we'll show how to make our APP receive those files and download them in the browser. This differs slightly from the usual process, where files are typically hosted on a server and downloaded from there. In this case, we'll make an HTTP call, receive a file, and download it.

Creating the Endpoint to Return a CSV

First, we'll create a GET endpoint with the route /test-csv. If you want to learn how to create an endpoint in your mock API, you can refer to this article. We won't add anything to the body since we're not returning JSON or XML; instead, we'll return a file from our mock server.

To make our mock API return a file, navigate to the headers tab and add a Content-Type header to our endpoint. The value of this header should be text/csv since we're returning a CSV file. This ensures that every time we make a GET request to this endpoint, it will return a CSV file instead of JSON or XML.

For now, we don't support custom file uploads for returning files. However, since this is a mock server, this approach should be sufficient for testing from our app that files are being downloaded.

We also support the downloading of PDF files from our mock API. It's as simple as changing the value of the header we set to application/pdf.

Once we've done this, we'll see something like the following in the body of our endpoint: "//Serving PDF file. Check out the headers tab."

Downloading the File from Our APP

Since this file is not hosted on a server, but is returned through a request to our mock API, we need to handle the client-side download in a way that feels seamless to the user. For this example, we'll use axios to make the request and then use native JS to download the file:

const exportData = async (fileName) => {
    const response = await axios.get('https://api.mockfly.dev/mocks/:slug/test-csv', {
      headers: { accept: 'text/csv' },
      responseType: 'arraybuffer',
    })

    const blob = new Blob([response.data], {
      type: 'text/csv',
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')

    a.href = url

    a.download = `${fileName}.csv`
    a.click()
}

This function makes a call to our mock API at the endpoint we created to return a CSV. It then uses the response to generate a file and download it in the browser. In this way, we can mock an API to return a file and make our mock server behave almost like a real server.