21 : Deleting a Job Post

  

Expired job posts need to be deleted, In this post, we will implement the logic for deletion. Again we will start with a failing test and then we will implement our logic so as to pass the failing test. Lets cook the test in tests > test_routes > test_jobs.py.

import json
from fastapi import status   #new


#... already existing code
#...

def test_delete_a_job(client):            #new
    data = {
        "title": "New Job super",
        "company": "doogle",
        "company_url": "www.doogle.com",
        "location": "USA,NY",
        "description": "fastapi",
        "date_posted": "2022-03-20"
        }
    client.post("/jobs/create-job/",json.dumps(data))
    msg = client.delete("/jobs/delete/1")
    response = client.get("/jobs/get/1/")
    assert response.status_code == status.HTTP_404_NOT_FOUND

This is a better test than the test for updation because we are not just relying on success msg, instead, we are actually testing the existence of the job-post. Now, if we run our test using pytest, It is sure to fail. So, let's create a route that will support deletion. Type the following code in apis > version1 > route_jobs.py

from db.repository.jobs import delete_job_by_id

@router.delete("/delete/{id}")
def delete_job(id: int,db: Session = Depends(get_db)):
    current_user_id = 1
    message = delete_job_by_id(id=id,db=db,owner_id=current_user_id)
    if not message:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Job with id {id} not found")
    return {"msg":"Successfully deleted."}

One last thing, we need to query the database and delete the record. And this logic we are putting in db > repository > jobs.py

def delete_job_by_id(id: int,db: Session,owner_id):
    existing_job = db.query(Job).filter(Job.id == id)
    if not existing_job.first():
        return 0
    existing_job.delete(synchronize_session=False)
    db.commit()
    return 1

Let's see our logic in action.

Prev: 20 : Updating … Next: 22 : JWT …
FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial