fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

"GET /audioFileType HTTP/1.1" 422 Unprocessable Entity

Open bytehealer opened this issue 5 years ago • 6 comments

hello Folks:

I am using fastapi along with mongodb database. but i am getting " 422 Unprocessable Entity" for get request. My app.py code is as below:

from fastapi import FastAPI
from fastapi.testclient import TestClient
from models import db, AudioFileType, Song, Podcast, AudioBook, audioFileMetadata

#defining app
app = FastAPI()

#get request for file type and audiofileID
@app.get('/audioFileType')
async def read_audioFileType(audioFileType: AudioFileType):
    return 'ok'
    audioList = []
    if hasattr(audioFileType, 'song') :
        for audiofile in db.audioList.find():
            audioList.append(Song(**audiofile))
        return { 'audioFileType': audioList }
    
    elif hasattr(audioFileType, 'podcast'):
        for audiofile in db.audioList.find():
            audioList.append(Podcast(**audiofile))
        return { 'audioFileType': audioList }
    
    else:
        for audiofile in db.audioList.find():
            audioList.append(AudioBook(**audiofile))
        return { 'audioFileType': audioList }   

@app.get("/audioFileType/{audioFileID}")
def read_audio(audioFileID: int):
    return db["audioFileID": audioFileID-1]

#Test
client = TestClient(app)
def test_read_audio():
    response = client.get("/audioFileType/{audioFileID}")
    assert response.status_code == 200
    assert response.json() == {"msg": {audioFileID -1}}

#create API
@app.post("/audios")
async def create_audio(audio: AudioFileType):
    #checking if record exist already inside all three types
    if hasattr(audio, 'song'):
        if hasattr('song', 'id'):
            delattr(audio, 'id')
            ret = db.audio.insert_one([audio.dict(by_alias=True), metadata])
            audio.id = ret.inserted_id
            return {'audio': audio}

    if hasattr(audio, 'podcast'):
        if hasattr('podcast', 'id'):
            delattr(podcast, 'id')
            ret = db.audios.insertMany([audio.dict(by_alias=True), metadata])
            audio.id = ret.inserted_id
            return {'audio': audio}

    if hasattr(audio, 'audiobook'):
        if hasattr('audiobook', 'id'):
            delattr(audiobook, 'id')
            ret = db.audio.insert_one(audio.dict(by_alias=True), metadata)
            audio.id = ret.inserted_id
            return {'audio': audio}

#delete
@app.delete("/audioFileType/{id}")
async def delete_audio(audioFileType: AudioFileType, id : str):
    if hasattr(audioFileType, 'song'):
        songtodelete = await db.find_one({ "id": ObjectId(id)})
        if songtodelete:
            await db.delete_one({"id": ObjectId(id)})
            return True
    if hasattr(audioFileType, 'podcast'):
        podcasttodelete = await db.find_one({ "id": ObjectId(id)})
        if podcasttodelete:
            await db.delete_one({"id": ObjectId(id)})
            return True
    if hasattr(audioFileType, 'audiobook'):
        audiobooktodelete = await db.find_one({ "id": ObjectId(id)})
        if audiobooktodelete:
            await db.delete_one({"id": ObjectId(id)})
            return True

#update
@app.put("audioFileType/{id}")
async def update_audio(audioFileType: AudioFileType, id: str):
    if len(audioFileType) < 1:
        return False
    if hasattr(audioFileType, 'song'):
        songtoupdate = await db.find_one({"id": ObjectId(id)})
        updated_song = await db.update_one (
            {"_id": ObjectId(id)}, {"$set": audioFileType}
        )
        if updated_song:
            return True
        return False
    if hasattr(audioFileType, 'podcast'):
        podcasttoupdate = await db.find_one({"id": ObjectId(id)})
        updated_podcast = await db.update_one (
            {"_id": ObjectId(id)}, {"$set": audioFileType}
        )
        if updated_podcast:
            return True
        return False
    if hasattr(audioFileType, 'audiobook'):
        audiobooktoupdate = await db.find_one({"id": ObjectId(id)})
        updated_audiobook = await db.update_one (
            {"_id": ObjectId(id)}, {"$set": audioFileType}
        )
        if updated_audiobook:
            return True
        return False
        ```
while my mongo file is as below:

from pydantic import BaseModel, Field from pymongo import MongoClient from bson import ObjectId from typing import Optional, List from datetime import datetime, date

client = MongoClient() db = client.audiobase

class PyObjectId(ObjectId):

@classmethod
def __get_validators__(cls):
    yield cls.validate

@classmethod
def validate(cls, v):
    if not ObjectId.is_valid(v):
        raise ValueError('Invalid objectid')
    return ObjectId(v)

@classmethod
def __modify_schema__(cls, field_schema):
    field_schema.update(type='string')

#defining class song using basemodel, mongodb id field starts with id but pydantic did not accept any field startting with ""

class Song(BaseModel): id: PyObjectId = Field(alias='_id') name: str duration: int uploaded_time: datetime

class Podcast(BaseModel): id: PyObjectId = Field(alias='_id') name: str duration: int uploaded_time: datetime host: str participants: str

class AudioBook(BaseModel): id: PyObjectId = Field(alias='_id') title: str author: str narrator: str duration: int uploaded_time: datetime

class Config: arbitrary_types_allowed = True json_encoders = { ObjectId: str }

class AudioFileType(BaseModel): song: List[Song] podcast: List[Podcast] audioBook: List[AudioBook]

class audioFileMetadata(BaseModel): id: PyObjectId = Field(alias='_id') metadata = str

Can anyone put forth his/her thought on that?
Thanks!

bytehealer avatar Mar 15 '21 16:03 bytehealer

Hi, Please can you provide the exact link that is returning 422.

Looking at your first get request, it is expecting a path parameter of type: AudioFileType . Considering the definition given by you for AudioFileType, the link will need to looking like this /{song: [], podcast: [], audioBook: []} for it to be validated successfully.

So, I guess you are not using the correct path parameter type.

olarid7852 avatar Mar 15 '21 21:03 olarid7852

image From browser here:

{
"detail": [
{
"loc": [
"body"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
```

bytehealer avatar Mar 16 '21 01:03 bytehealer

Hi, Please can you provide the exact link that is returning 422.

Looking at your first get request, it is expecting a path parameter of type: AudioFileType . Considering the definition given by you for AudioFileType, the link will need to looking like this /{song: [], podcast: [], audioBook: []} for it to be validated successfully.

So, I guess you are not using the correct path parameter type.

yes and the model for song, podcast and audiobook has been defined in model.py and further i would like to search in the database for that particular audiofiletype and will return all of them based upon the condition for search parameter defined. I hope i am not making mistake there.

bytehealer avatar Mar 16 '21 01:03 bytehealer

When you do:

async def read_audioFileType(audioFileType: AudioFileType):

You're expecting a body, which is precisely what is being pointed out in the error message:

{
    "detail": [
        {
            "loc": [
                "body"   // Problem location.
            ],
            "msg": "field required",  // Clear message on what's happening.
            "type": "value_error.missing"
        }
    ]
}

This is a get endpoint, it's recommended for this method to not have a body field. You should consider using post instead. But if you insist, just be aware that is not supported by Swagger.

Now, non related, non asked comments:

  • Developers are artists. Please share your art properly: https://www.freecodecamp.org/news/how-to-format-code-in-markdown/#:~:text=There%20are%20two%20ways%20to,will%20apply%20syntax%20highlighting%20to.
  • You're using coroutines (async), but you're using pymongo. Either use motor with async or change the signature to def. This is not the place to talk about it, if you want to know more about it, google it or search on this GitHub issues, you'll find out the answer.

Kludex avatar Mar 16 '21 01:03 Kludex

Thanks for the help here @olarid7852 and @Kludex ! 👏 🙇

If that solves the original problem, then you can close this issue @mannawar ✔️

Sorry for the long delay! 🙈 I wanted to personally address each issue/PR and they piled up through time, but now I'm checking each one in order.

tiangolo avatar Nov 27 '22 17:11 tiangolo

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

github-actions[bot] avatar Dec 08 '22 00:12 github-actions[bot]