Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 114 additions & 62 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,85 +1,137 @@
# <img src="https://cloud.githubusercontent.com/assets/7833470/10423298/ea833a68-7079-11e5-84f8-0a925ab96893.png" width="60"> Personal API - Weekend Lab
#Band Custom API

It's time to have some fun and play with the technologies you've learned in the past week. Your goal is to start your own API.
Hello, I have designed an API that allows and enables bands to have a page where bands can have a database/page
of information. Bands can sign up for an account and have page where they can display albums in an easy and organized fashion.

Your API can be related to whatever you like, but its Mongo DB must have at least 2 schemas/models that are connected by reference.
##https://nameless-ocean-65089.herokuapp.com/band

For example, if your API is for keeping track of various hotels, it would need to reference another type of object besides hotels. You might choose to provide more information about the cities your hotels are found in beyond a simple string like "Austin" or "Orlando". Your `City` schema/model could contain information about the city iself like city name, state, local attractions, and of course a list of related hotels connected by reference.
Here bands can add information about themselves. Simply fill out questions to the the model below.

### Your API should have:

* Well-organized **JSON API** Endpoints
* The ability to **read** (`GET`) each type of resource **as a collection**
* The ability to **read** (`GET`) each type of resource **by specific ID**
* The ability to **create** (`POST`) a new resource of each type
* At least one **update** (`PUT`) endpoint
* At least one **delete** (`DELETE`) endpoint

Try to start by completing the schema/model and implementing endpoints for only one type of resource and expand from there to include other schemas/models/endpoints.

Fork and clone this repo. You can use the placeholder code in this repo as a starting point.

## Step 0: Deploy to Heroku

Before we start coding, let's prepare to deploy our API on Heroku so other developers can access our API from any computer.

You can find full instructions here: [Deploying Express Apps to Heroku](https://github.com/SF-WDI-LABS/shared_modules/blob/master/how-to/heroku-mean-stack-deploy.md)

As you continue to work on this project, you'll need to remember to push your changes to Heroku (just like you would with Github!):

```bash
# git add changed-files
# git commit -m "detailed description of what I changed"
git push heroku master
heroku open
```
name: String,
origin: String,
genre: String,
established: Date
```

It's common for code to break "in production" even when it works fine "in development" on your computer (due to different environment variables, missing dependenies, etc). Do your best to debug! Let us know if you get stuck on deployment issues.

## Step 1: Verify the Test Routes in Postman

Since we're building a JSON API with no front-end (yet), Postman will come in handy for testing our work.

Make sure you've **installed dependencies** and added a `.env` file with your **Mongo DB credentials**. Then **run the server** with the placeholder code.

Use Postman to verify that the `GET /test` and `POST /test` endpoints work, confirming that our server can connect to our Mongo DB and complete operations on demand. For the `POST` endpoint, you can simply submit an object with a `name` property, and then it should appear in your next `GET /test` request:

```json
{
"name": "test item 1"
}
```
app.get('/band', bandRoutes.displayBandItems);
app.get('/band/:id', bandRoutes.displayBandItem);
app.post('/band', bandRoutes.createBandItem);

function displayBandItems(req, res) {
db.Band.find({}, function(err, data){
// console.log('am i working', db);
if (err) {
console.log('Error retrieving band items from DB.', err);
res.status(500).send('Internal server error');
} else {
res.json(data);
}
});
}

## Step 2: Build Your Main Schema/Model

Next, go to the `models/` folder and add a new file for your main schema/model. For now we'll create it without a reference to any other schemas/models.
function createBandItem(req, res) {
const newBandItem = db.Band({
name: req.body.name,
origin: req.body.origin,
genre: req.body.genre,
established: req.body.established
});

Be sure to export the model from the file and then modify `models/index.js`. It should require the file you just created and then export the models from it so they can be used more directly while preparing responses for our routes.
newBandItem.save(function(err, data){
if (err){
console.log('error saving band item to data bas', err);
res.status(500).send('Internal server error');
} else {
res.status(201).json(data);
}
```

## Step 3: Create Your Primary Endpoints

Now go to the `routes/` folder and create a new file to handle your endpoints for the primary model. It should contain function definitions for handling various endpoints (`GET`, `POST`, etc) related to your primary model.

Start with the `GET` method for retrieving all matching resources. Then add a function for adding new resources (`POST`). Then add a function for retireving a specific resource by ID (`GET`, with path parameter).
##https://nameless-ocean-65089.herokuapp.com/album

Make sure that for each function, you modify `server.js` to register the functions as endpoint/route handlers.
In order for a band to add an album to their discography I have developed a model that would allow them to simply enter the required fields. Adding tags would help broaden their chances of reaching more people.

## Step 4: Check Your Work in Postman
Below you will find the code in which this would allow bands to add albums to their page.
```
name: {
type: String,
unique: true,
required: true
},
imageUrl: {
type: String,
default: ""
},
tags: [{
type: String,
default: ""
}],
```

Open up Postman with your new code running on `localhost`. Hit your new `GET` and `POST` endpoints a few times to verify everything is working as expected.
```
const albumRoutes = require('./routes/albums');
app.get('/album', albumRoutes.displayAlbumItems);
app.get('/album/:id', albumRoutes.displayAlbumItem);
app.post('/album', albumRoutes.createAlbumItem);
```

If it's all working, add/commit your changes to git. Push to Github to backup your code. Push to Heroku so other people can use your newly created endpoints.

Return to Postman and test again, making sure that your code is working "in production" on the URL Heroku provided for your API server.
```
function displayAlbumItems(req, res) {
db.Album.find({}, function(err, data){
// console.log('am i working', db);
if (err) {
console.log('Error retrieving band items from DB.', err);
res.status(500).send('Internal server error');
} else {
res.json(data);
}
});
}
function displayAlbumItem(req, res) {
db.Album.findOne({_id: req.params.id}, function(err, data){
// console.log('am i working', db);
if (err) {
console.log('Error retrieving band items from DB.', err);
res.status(500).send('Internal server error');
} else {
res.json(data);
}
});
}
function createAlbumItem(req, res) {
const newAlbumItem = db.Album({
name: req.body.name,
imageUrl: req.body.imageUrl,
tags: []

});
};
```

## Step 5: Add Your Other Schemas/Models/Endpoints
#https://nameless-ocean-65089.herokuapp.com/band/59dd48e7f73ece00125b0db6

Now it's time to expand on what you've done. Piece by piece, add the other schemas/models and endpoints you planned.
In order to get to pull or grab a single band I have created a route where each band who is has signed up will be given a personal id in which they "live" and can be called upon.

Be sure to test your endpoints as you go in Postman. Also don't forget to commit your changes and deploy to Heroku from time to time.
Below is the code I used in order to get a band by id.

## Options for Extra Challenge
```
app.get('/band/:id', bandRoutes.displayBandItem);

function displayBandItem(req, res) {
db.Band.findOne({_id: req.params.id}, function(err, data){
// console.log('am i working', db);
if (err) {
console.log('Error retrieving band items from DB.', err);
res.status(500).send('Internal server error');
} else {
res.json(data);
}
});
}

- **Add even more schemas/models/enpoints.** Thinking of more detailed information is usually fairly easy, but the code to support it gets more difficult the more detail is added.
- **Add support for query parameters** to limit/filter responses on your endpoints that retrieve all resources in a collection. For example, you might limit items based on rating, time/date range, tags, etc.
- **Document all the endpoints of your API** in a markdown file. What does each endpoint do? How should a new user of your API get started?
```
26 changes: 26 additions & 0 deletions models/album-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const mongoose = require('mongoose');



const AlbumSchema = new mongoose.Schema({
name: {
type: String,
unique: true,
required: true
},
imageUrl: {
type: String,
default: ""
},
tags: [{
type: String,
default: ""
}],

});

const Album = mongoose.model('Album', AlbumSchema);

module.exports = {
Album: Album,
};
15 changes: 15 additions & 0 deletions models/band-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose = require('mongoose');
// const Schema = mongoose.Schema();

const BandSchema = new mongoose.Schema({
name: String,
origin: String,
genre: String,
established: Date
});

const Band = mongoose.model('Band', BandSchema);

module.exports = {
Band: Band
}
14 changes: 10 additions & 4 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const mongoose = require('mongoose');
require('dotenv').config();
// TODO: include all model files here (and export models together below)
const testModels = require('./test');

// TOdo: include all model files here (and export models together below)
// const testModels = require('./test');
const bandModels = require('./band-schema');
const albumModels = require('./album-schema');


// connect to Mongo DB
mongoose.connection.openUri(process.env.MONGODB_URI || process.env.DB_CONN, {}, function(err, conn) {
Expand All @@ -13,6 +17,8 @@ mongoose.connection.openUri(process.env.MONGODB_URI || process.env.DB_CONN, {},
});

module.exports = {
// TODO: add references to all models here
Test: testModels.Test
// TOdo: add references to all models here
// Test: testModels.Test,
Band: bandModels.Band,
Album: albumModels.Album
};
Loading