1

I am creating a GET request in FastAPI as follows:

@router.get("/{ngo_id}")
def get_ngo_by_id(ngo_id: str):
    
    # Get the NGO from the database
    db = firestore.client()
    ngo_ref = db.collection("ngos").document(ngo_id).get()
    ngo_data = ngo_ref.to_dict()

    # Return the NGO
    if ngo_data:
        return JSONResponse(
            status_code=response_status.HTTP_200_OK,
            content={
                "message": "Success",
                "data": jsonable_encoder({ngo_ref.id: ngo_ref.to_dict()}),
            },
        )
    else:
        return JSONResponse(
            status_code=response_status.HTTP_404_NOT_FOUND,
            content={"message": "NGO not found", "data": None},
        )

This is how it shows up in my swagger.

enter image description here

In this case the example value just says "string" and the schema is empty. I want to show a schema and an example value but I am NOT using a Pydantic model for the GET request.

My example value should show what the output of the NGO structure would look like and it's as follows.

{
  "message": "Success",
  "data": {
    "7kKMwGsTyRD00tjY1zpb": {
      "description": "string",
      "website": "string",
      "associatedMagazines": [
        "string"
      ],
      "contactNumber": "string",
      "tagline": "string",
      "displayName": "string",
      "contactName": "string",
      "createdBy": "string",
      "updatedBy": "string",
      "updatedOn": "string",
      "createdOn": "string",
      "associatedProjects": [
        "string",
      ],
      "publicRegistryId": null,
      "status": "string",
      "contactEmail": "string",
      "docID": "string",
      "isFeatured": false,
      "bannerUrl": [
        "string"
      ],
      "logoUrl": "string"
    }
  }
}

How can I achieve this?

Prakhar Rathi
  • 905
  • 1
  • 11
  • 25
  • 3
    Why are you not using a pydantic model for the request? – M.O. Apr 19 '23 at 06:21
  • 1
    You should still use a pydantic response model even if you're not using a pydantic model _for the request_. You can either use `@router.get(..., response_model=NGOResponse)` on the route decorator, or you can type the function with returning `NGOResponse`: `def get_ngo_by_id(ngo_id: str) -> NGOResponse`. – MatsLindh Apr 19 '23 at 07:57
  • 1
    You may find the following posts helpful: [this](https://stackoverflow.com/a/73305895/17865804), [this](https://stackoverflow.com/a/71029291/17865804), as well as [this](https://stackoverflow.com/a/75726285/17865804) and [this](https://stackoverflow.com/a/76021150/17865804) – Chris Apr 19 '23 at 09:31
  • @MatsLindh that makes sense. I will use a response model separately. Thanks – Prakhar Rathi Apr 20 '23 at 06:10
  • @M.O. Thanks, I will use the model now. – Prakhar Rathi Apr 20 '23 at 06:10

0 Answers0