Test with Swagger
Start the server and test your POST endpoint in the browser
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Start the server with uvicorn
Your Python file defines the API, but it cannot listen for requests on its own. Uvicorn is the server that bridges the network to your FastAPI application.
The command uvicorn main:app --reload does three things:
main:app: tells uvicorn to find theappobject inmain.py.--reload: restarts the server automatically when you save changes to your code.- Starts listening on
http://127.0.0.1:8000.
Interactive documentation at /docs
FastAPI generates a Swagger UI page at http://127.0.0.1:8000/docs. This page lists every endpoint in your API with a "Try it out" button for each one.
Open /docs in your browser after starting the server. You will see your POST /expenses endpoint listed.
Test the POST endpoint
Click POST /expenses, then click Try it out. Paste this JSON into the request body:
{
"description": "Lunch",
"amount": 12.50,
"category": "food"
}Click Execute. You should see a 201 response with the expense data plus an id field.
Test validation
Try sending invalid data to see your validation rules in action:
- Empty description:
{"description": "", "amount": 10, "category": "food"}returns a422error. - Negative amount:
{"description": "Test", "amount": -5, "category": "food"}returns a422error. - Invalid category:
{"description": "Test", "amount": 10, "category": "xyz"}returns a422error.
Every rule you defined in your Expense model is enforced automatically. You wrote zero validation logic in your endpoint.
Instructions
Start the development server.
- Run
uvicorn main:app --reload.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding