FastAPI: How to Return a TXT or JSON File

Updated: May 16, 2023 By: Goodman Post a comment

This concise, practical article shows you how to return a TXT or a JSON file in FastAPI. I assume you already have some understanding of the web framework, so I won’t waste your time by explaining what FastAPI is, how well it works, or rambling about its history. Let’s get straight to the main points.

Returning a TXT file

A TXT file is a plain text file that contains only text and no images or other non-text characters1. It can be opened and edited by any text editor, such as Notepad or TextEdit. TXT files are often used to store human-readable data like notes, instructions, logs, or other text-based information.

In FastAPI, you can return a TXT file by using PlainTextResponse, which will set the content-type header to text/plain.

Example:

# slingacademy.com
# main.py
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()

# returns a TXT file with your dynamic data
@app.get("/welcome.txt")
async def get_txt():
    text = "Welcome to Sling Academy."
    return PlainTextResponse(text)  

# returns a TXT file from disk
@app.get("/static_data.txt")
async def get_txt_file():
    file_name = "data.txt"

    # Assume that the file is in the root directory of the project.
    file_path = f"./{file_name}"
    
    file = open(file_path, "r")
    return PlainTextResponse(file.read())

Now start your API in the development mode:

uvicorn main:app --reload

Then go to http://localhost:8000/welcome.txt and http://localhost:8000/static_data.txt. In order for the later route to work, don’t forget to create a plain text file named data.txt in the root directory of your project.

Returning a JSON file

Live Demo: The URL below leads to a JSON file which is returned by Sling Academy’s public API (built with FastAPI):

https://api.slingacademy.com/v1/sample-data/files/customers.json

You can see other interesting stuff made with FastAPI on this page. Now, let’s focus on the question: How to return a JSON file? The answer depends on your need:

  • If you want to serve dynamic JSON data (fetched from a database or created dynamically), use JSONResponse, which will automatically convert your data to JSON and set the appropriate content-type header.
  • If you want to return a JSON file from disk, use FileResponse.

This code example will clarify what I mean:

# slingacademy.com
# main.py

from fastapi import FastAPI
from fastapi.responses import JSONResponse, FileResponse

app = FastAPI()

# Return a JSON response with the data
# You can fetch data from a database or create it dynamically
@app.get("/hello.json")
async def get_hello():
    data = {
        "hello": "world",
        "foo": "bar",
        "sling": "academy"
    }

    return JSONResponse(data)

# Return a JSON response with a JSON file from disk
@app.get("/data.json")
async def get_data():
    filename = "data.json"

    # assume the file is in the root directory of the project
    file_path = f"./{filename}"

    return FileResponse(filename)

Add a JSON file named data.json to the root directory of your project (the content of the file doesn’t matter as long as the JSON syntax is valid). Boot your API up then go to http://localhost:8000/hello.json and http://localhost:8000/data.json. Cheer!