A simple REST API built with Go (Golang) and MongoDB for performing CRUD operations on user data.
- Go 1.16 or higher
- Docker and Docker Compose
- Postman (for testing the API)
testapi/
├── docker-compose.yml
├── .env
├── main.go
├── models/
│ └── user.go
└── handlers/
└── user_handler.go
- Clone the repository:
git clone <your-repo-url>
cd testapi
- Start MongoDB using Docker:
docker-compose up -d
- Run the application:
go run main.go
The server will start on http://localhost:8080
- Method: POST
- URL:
http://localhost:8080/users
- Headers:
- Content-Type: application/json
- Request Body:
{
"name": "John Doe",
"email": "[email protected]",
"age": 30
}
- Success Response:
- Status: 200 OK
- Returns the created user ID
- Method: GET
- URL:
http://localhost:8080/users
- Success Response:
- Status: 200 OK
- Returns array of users
- Method: GET
- URL:
http://localhost:8080/users/{id}
- URL Parameters: id=[string] (MongoDB ObjectID)
- Success Response:
- Status: 200 OK
- Returns user object
- Method: PUT
- URL:
http://localhost:8080/users/{id}
- URL Parameters: id=[string] (MongoDB ObjectID)
- Headers:
- Content-Type: application/json
- Request Body:
{
"name": "John Updated",
"email": "[email protected]",
"age": 31
}
- Success Response:
- Status: 200 OK
- Returns update result
- Method: DELETE
- URL:
http://localhost:8080/users/{id}
- URL Parameters: id=[string] (MongoDB ObjectID)
- Success Response:
- Status: 200 OK
- Returns delete result
- Open Postman
- Create a new Collection called "User API"
- Add new requests for each endpoint:
- Create new POST request to
http://localhost:8080/users
- Go to Headers tab:
- Add
Content-Type: application/json
- Add
- Go to Body tab:
- Select "raw"
- Choose "JSON" from dropdown
- Add user JSON object
- Create new GET request to
http://localhost:8080/users
- No additional headers or body needed
- Create new GET request to
http://localhost:8080/users/{id}
- Replace {id} with actual user ID from create response
- Create new PUT request to
http://localhost:8080/users/{id}
- Add same headers as Create User
- Add updated user JSON in body
- Create new DELETE request to
http://localhost:8080/users/{id}
- Replace {id} with actual user ID
The application uses following environment variables (stored in .env):
MONGODB_URI
: MongoDB connection stringDATABASE_NAME
: Name of the database
The API returns appropriate HTTP status codes:
- 200: Success
- 404: Resource not found
- 500: Server error
MongoDB runs in Docker container with following credentials:
- Host: localhost
- Port: 27017
- Username: admin
- Password: password
- Stop the Go server with Ctrl+C
- Stop MongoDB container:
docker-compose down
User model structure:
type User struct {
ID primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Age int `json:"age,omitempty" bson:"age,omitempty"`
}