This repository contains an implementation of a REST API using FastAPI, featuring user authentication, CORS support, and SQLite database integration. It serves as a quick-start template for building secure RESTful services with Python.
- User registration and authentication with JWT tokens
- CRUD operations for a simple "Item" resource
- User-specific item management
- SQLite database for persistent storage
- CORS middleware to allow cross-origin requests
- Pydantic models for request and response validation
- Automatic API documentation with Swagger UI
- Database viewer CLI tool
.
├── main.py
├── view_db.py
├── test.db (created when you run the application)
└── README.md
REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API (Application Programming Interface) is a way of accessing web services using HTTP protocols.
Key characteristics of a REST API include:
- Client-Server Architecture: Separation of concerns between the user interface and data storage.
- Statelessness: Each request from client to server must contain all the information needed to understand and process the request.
- Cacheability: Responses must define themselves as cacheable or non-cacheable.
- Uniform Interface: A consistent way of interacting with a given server irrespective of device or type of application.
- Layered System: Client cannot tell whether it is connected directly to the end server or to an intermediary along the way.
REST APIs typically use HTTP methods to perform CRUD (Create, Read, Update, Delete) operations:
- POST: Create a new resource
- GET: Read a resource
- PUT: Update an existing resource
- DELETE: Delete a resource
-
Install the required packages:
pip install fastapi uvicorn sqlalchemy passlib python-jose[cryptography] python-multipart python-dotenv
-
Create a
.env
file in the project root and add a secret key:SECRET_KEY=your_secret_key_here
-
Run the server:
python main.py
Or use uvicorn directly:
uvicorn main:app --reload
-
Open your browser and go to
http://localhost:8000/docs
to see the Swagger UI documentation and test the API.
POST /register
: Register a new userPOST /token
: Login and receive an access token
POST /items/
: Create a new itemGET /items/
: Get all items for the authenticated userGET /items/{item_id}
: Get a specific item by IDPUT /items/{item_id}
: Update an itemDELETE /items/{item_id}
: Delete an item
The view_db.py
script provides a CLI tool to view the contents of the database. This improved version provides a command-line interface with several options:
- View all tables in the database
- View all items
- View all users (without showing hashed passwords)
- View items belonging to a specific user
To use this tool, you can run it from the command line with different arguments. Here are some example commands:
-
To view all tables:
python view_db.py tables
-
To view all items:
python view_db.py items
-
To view all users:
python view_db.py users
-
To view items belonging to a user with ID 1:
python view_db.py user_items --user_id 1
CORS is enabled for all origins, methods, and headers. In a production environment, you should restrict these to only the necessary origins, methods, and headers.
The application uses SQLite, a lightweight, file-based database. The database file (test.db
) will be created in the same directory as main.py
when you run the application for the first time.
- The SECRET_KEY in the .env file should be kept secret and not shared or committed to version control.
- In a production environment, consider using a more robust database like PostgreSQL.
- Implement additional security measures such as rate limiting and more granular permissions as needed.
While this implementation provides a solid foundation, consider the following enhancements for a production environment:
- Implement refresh tokens for better security
- Add email verification for user registration
- Implement password reset functionality
- Add more complex validation and error handling
- Implement pagination for large datasets
- Add unit and integration tests
- Containerize the application with Docker
- Implement logging for better debugging and monitoring
- Consider using asynchronous database queries for improved performance
This template provides a robust starting point for building secure, authenticated REST APIs with FastAPI. Feel free to extend and modify it to suit your specific project needs!