Coding sample for Getting Started with FastAPI documentation page. A simple FastAPI project demonstrating JWT authentication with token-based access. This project includes endpoints for user sign-up, login, and accessing secure and public data.
👉 For more FastAPI Resources please access:
- Python 3.7+
pipfor package management
Install dependencies:
pip install fastapi sqlalchemy pydantic passlib[bcrypt] python-jose uvicornThis project uses SQLite for the database.
- Create Database and Tables:
When you run the project the database and table would automatically be created.
To start the FastAPI server, use the following command:
uvicorn main:app --reloadThe server will be available at http://127.0.0.1:8000.
Registers a new user with a username and password.
-
Method:
POST -
URL:
http://127.0.0.1:8000/signup -
Request Body:
{ "username": "newuser", "password": "newpassword" } -
Example:
curl -X POST "http://127.0.0.1:8000/signup" \ -H "Content-Type: application/json" \ -d '{ "username": "newuser", "password": "newpassword" }'
Authenticates a user and returns a JWT token.
-
Method:
POST -
URL:
http://127.0.0.1:8000/token -
Request Body (Form Data):
Key Value username usernamepassword password -
Example:
curl -X POST "http://127.0.0.1:8000/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=newuser&password=newpassword"
-
Response:
{ "access_token": "your_jwt_token", "token_type": "bearer" }
Returns secure data and requires a valid JWT token for access.
-
Method:
GET -
URL:
http://127.0.0.1:8000/secure-data -
Headers:
Authorization: Bearer YOUR_ACCESS_TOKEN -
Example:
curl -X GET "http://127.0.0.1:8000/secure-data" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
-
Response:
{ "msg": "Hello, newuser. You have access to secure data!" }
An open endpoint that does not require authentication.
-
Method:
GET -
URL:
http://127.0.0.1:8000/public -
Example:
curl -X GET "http://127.0.0.1:8000/public" -
Response:
{ "msg": "This is a public route!" }
. ├── main.py # Main FastAPI application ├── models.py # Pydantic and SQLAlchemy models ├── auth.py # Authentication functions (JWT) ├── database.py # Database configuration and session management └── README.md # Project documentation fastapi- Web framework for building APIs.sqlalchemy- ORM for interacting with SQLite database.pydantic- Data validation for request and response models.passlib[bcrypt]- Password hashing library.python-jose- For handling JWT encoding and decoding.uvicorn- ASGI server for FastAPI.
- Replace
"YOUR_ACCESS_TOKEN"incurlexamples with the actual token obtained from the login endpoint. - Update
DATABASE_URLindatabase.pyif you switch to another database (e.g., PostgreSQL). - To access Swagger documentation, visit:
http://127.0.0.1:8000/docs.
Getting Started with FastAPI - Coding sample provided by App Generator