{"id":19635752,"url":"https://github.com/codepath/server-api-template","last_synced_at":"2025-04-28T08:31:03.467Z","repository":{"id":7499514,"uuid":"8849120","full_name":"codepath/server-api-template","owner":"codepath","description":"Basic Rails+Grape template for creating RESTful APIs","archived":false,"fork":false,"pushed_at":"2013-03-18T08:32:37.000Z","size":390,"stargazers_count":11,"open_issues_count":0,"forks_count":21,"subscribers_count":9,"default_branch":"master","last_synced_at":"2023-05-10T14:13:30.974Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codepath.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-03-18T07:29:55.000Z","updated_at":"2020-05-18T00:02:30.000Z","dependencies_parsed_at":"2022-07-14T23:46:09.109Z","dependency_job_id":null,"html_url":"https://github.com/codepath/server-api-template","commit_stats":null,"previous_names":[],"tags_count":0,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fserver-api-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fserver-api-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fserver-api-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codepath%2Fserver-api-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codepath","download_url":"https://codeload.github.com/codepath/server-api-template/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224102102,"owners_count":17256094,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-11T12:26:49.617Z","updated_at":"2024-11-11T12:26:50.964Z","avatar_url":"https://github.com/codepath.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Server API Template\n\nThis is our CodePath template for giving people an easy way to create RESTful JSON APIs\nto power their applications.\n\n## Outline\n\n - [Installation](#installation)\n - [Building APIs](#building-apis)\n - [Quick Reference](#quick-reference)\n - [Deploying to Heroku](#deploying)\n\n## Libraries\n\nThis project is using several libraries and frameworks:\n\n - [Rails 3.2](http://rubyonrails.org/) - Web Framework\n - [Grape](http://rdoc.info/github/intridea/grape) - API endpoints\n - [Devise](https://github.com/plataformatec/devise) - Authentication\n - [RailsAdmin](https://github.com/sferik/rails_admin) - Database dashboard\n - [MiniTest](https://github.com/seattlerb/minitest) - Unit testing\n\n## Installation\n\n### Dependencies\n\nMake sure you have Ruby 1.9.3 and Git installed. Type into the terminal:\n\n```bash\n$ ruby -v\n```\n\nThen type into the terminal:\n\n```bash\n$ git --version\n```\n\nVerify you see \"ruby 1.9.3pXXX\" (where the XXX can be any number). If not then download and run [RailsInstaller](http://railsinstaller.org/) in order to get Ruby.\n\nIf you get an error of \"no git command\", then download and run\n[RailsInstaller](http://railsinstaller.org/) in order to get git.\n\n### GitHub\n\nThe first step is to register a [github account](https://github.com/) (if you don't have one yet) which allows you\nto store your code for free on the github servers.\n\nYou probably need to [upload your ssh key](https://help.github.com/articles/generating-ssh-keys) to Github\nin order to get or push repositories:\n\n```bash\n$ pbcopy \u003c ~/.ssh/id_rsa.pub\n```\n\nIf that command fails with a file not found, run `$ ssh-keygen -t rsa -C \"your_email@example.com\"` to generate your SSH key.\n\nNext, go to your [ssh keys](https://github.com/settings/ssh) and paste the contents of your clipboard.\n\n### Fork and Clone\n\nNow we need to **fork this repository** to your own account at \u003chttps://github.com/thecodepath/server-api-template\u003e.\nYou can do that by clicking \"Fork\" on the top right.\n\nNext, you want to clone your version of this repository locally:\n\n```bash\n$ git clone git@github.com:myusername/server-api-template.git\n```\n\n**Note:** Be sure to replace `myusername` with your own bitbucket username above.\n\n### Setup\n\nRun the task to install dependencies:\n\n```bash\n$ bundle\n```\n\nWhen this is finished, let's prepare this as a new git repository (for storing code):\n\n```bash\n$ rm -rf .git\n$ git init\n$ git commit -am \"initial commit of my app\"\n$ git remote add origin git@bitbucket.org:myusername/server-api-template.git\n$ git push origin master --force\n```\n\n**Note:** Be sure to replace `myusername` with your own bitbucket username above for remote.\n\nNow setup your local database for use on your computer:\n\n```bash\n$ rake db:migrate db:test:prepare\n```\n\n### Running\n\nOnce you are setup, be sure to start your Rails application:\n\n```bash\n$ rails server\n```\n\nThis starts your API application at \u003chttp://localhost:3000\u003e so you\ncan try it locally. Try going to \u003chttp://localhost:3000/api/v1/sessions\u003e.\n\n## Building APIs\n\n### Define User Stories\n\nAlways start by defining user stories of what the user can do in your app. For example,\nwith twitter, you can:\n\n - Register an account\n - Post a tweet\n - See my tweets home timeline\n - Follow a user\n\n### Define Schema\n\nNext, define a schema based on resources.\n\n - Identify resources in your application (i.e user, tweets, favorites)\n - Identify attributes of each resource (i.e a tweet has a body, timestamp)\n - Identify the \"associations\" for each resource (i.e a tweet has a user_id)\n\nFor example with twitter, you have a `user` resource and a `tweets` resource\nand a tweet \"belongs to\" a user. A user has an email and a password and a tweet\nhas a body and a timestamp.\n\n### Create Models\n\nModels are the way that a Rails application stores data for your application resources.\nOn a high level:\n\n  - Use `rails g model \u003cNAME\u003e` to generate models for each resource\n    - `rails g model Tweet`\n  - Fill out the \"db/migrate/xxxxx\" file for each model\n  - Fill out associations for each model (i.e `belongs_to :user`)\n  - Fill out any validations for each model (i.e `validates :body, :presence =\u003e true`)\n\nFor example, imagine we want to create a \"Tweet\" resource that has a status and is created by a user. First,\nwe would generate the tweet resource:\n\n```bash\n$ rails g model tweet body:string user_id:integer\n```\n\nThis will generate a file in `db/migrate/xxxxxx_create_tweets.rb` that defines the fields\nfor the tweet (right now just a body and a number representing the user).\n\nNow we can run the migrations with `rake db:migrate` and then check out our\nmodel file at `app/models/tweet.rb`. Models are blank by default and often don't need any\nadditional code. The fields (body and user_id) will work automatically.\n\nWe can now create, update or destroy tweets from within our APIs:\n\n```ruby\n# create\ntweet = Tweet.create(:body =\u003e \"foo\", :user_id =\u003e 1)\n# update\ntweet.update_attribute(:body, \"bar\")\n# find\nmy_tweet = Tweet.where(:body =\u003e \"bar\").first\n# delete\nmy_tweet.delete\n```\n\nOnce we have our models, we can build the related API endpoints so our client mobile applications\ncan modify the resources.\n\n### Build Grape Resources\n\nIn Grape, APIs are defined in terms of \"resources\" which are different nouns within your application.\nAn 'endpoint' is a URL that creates, updates, returns or deletes resource data. For example, creating a new\ntweet, returning a list of tweets, deleting a tweet, et al. On a high level, APIs are defined through:\n\n  - Editing `app/api/endpoints` for various resource endpoint files\n  - Add resource declarations into grape endpoint files\n  - Write the endpoint code for each resource API\n\nAn API endpoint lives inside of `app/api/endpoints/someresource.rb` where \"someresource\" is\nthe noun being affected by the API. For instance, the API endpoint for registering\na new user lives in `app/api/endpoints/users.rb` and is described by the following:\n\n```ruby\nresource :users do\n  desc \"Register a new user\"\n  params do\n    requires :email, type: String, desc: \"email for user\"\n    requires :password, type: String, desc: \"password for user\"\n  end\n  post do\n    @user = User.new(params.slice(:email, :password))\n    if @user.save\n      status 201\n      @user.as_json\n    else # user didn't save\n      error!({ :error =\u003e \"user could not be registered\", :details =\u003e @user.errors }, 400)\n    end\n  end\nend\n```\n\nNotice that there are three main parts: description (`desc`) for describing the purpose, params for specifying\nrequired parameters for the API request and then the API code which starts with an HTTP request method such\nas `get`, `post`, `put`, or `delete`.\n\nBe sure to check out the [quick reference](#quick-reference) for better notes on how to\nselect a request method and/or response status codes.\n\nAPI endpoints are defined in terms of other resources (tweets, trips, appointments, etc)\nbased on the APIs and models in your application.\n\nFor example, a tweets endpoint for creating (POST) a new tweet would live in `app/api/endpoints/tweets.rb` and\nlook like this:\n\n```ruby\nresource :tweets do\n  desc \"Create a new tweet\"\n  params do\n    requires :body, type: String, desc: \"body for tweet\"\n    requires :user_id, type: String, desc: \"user for tweet\"\n  end\n  post do\n    @tweet = Tweet.new(params.slice(:body, :user_id))\n    if @tweet.save\n      status 201\n      @tweet.as_json\n    else # user didn't save\n      error!({ :error =\u003e \"tweet could not be created\", :details =\u003e @tweet.errors }, 400)\n    end\n  end\nend\n```\n\nand a method for getting (GET) all tweets for a user might look like:\n\n```ruby\nresource :tweets do\n  desc \"Gets a user's tweets\"\n  params do\n    requires :user_id, type: String, desc: \"user for tweet\"\n  end\n  get do\n    @tweets = Tweet.where(:user_id =\u003e params[:user_id])\n    @tweets.as_json\n  end\nend\n```\n\nYou simply need to identify the resources for you application, what\nactions can be taken on them (create, read, update or delete) and then\nimplement the endpoints accordingly.\n\n## Other Tasks\n\nHere's a list of a few other todos:\n\n  - In \"config/initializers/configure_api.rb\" configure the username / password for your authenticated APIs\n  - In \"app/api/api_router.rb\" uncomment lines to create basic authenticated endpoints.\n  - In \"config/environments/production.rb\" fill in the real domain for your application\n  - In \"config/initializers/airbrake.rb\" fill in the token for your free airbrake account (for error reporting)\n\n## Quick Reference\n\n### Key files\n\nKey files to edit:\n\n  - \"app/api/endpoints/*\" - Adding endpoints and APIs\n  - \"db/migrate\" - Defining the model attributes in the database\n  - \"app/models\" - Defining any additional model information\n  - \"test/api\"   - Defining tests for your APIs (if needed)\n\n### Key URLs\n\nFew URLs to note (once rails server is running):\n\n  - \"/api/sessions\" - Simple endpoint that returns text\n  - \"/rails/routes\" - See a list of common rails routes\n  - \"/users/sign_in\" - Login (or register) a user\n  - \"/admin\" - Admin panel for viewing database content\n\n### Request Methods\n\nAs a rule of thumb, the request method to pick is as follows:\n\n|Method|Description|Example|\n| ------ | ------ | ----- |\n|get|For returning resources from read-only endpoint|Get user tweets|\n|post|For creating new resources|Create new tweet|\n|put|For updating an existing resource|Editing a user's password|\n|delete|For deleting a resource|Trashing a tweet|\n\n\n### Response Status Codes\n\nAnother thing to notice is API response `status` codes, as a rule of thumb:\n\n|Status|Description|Example|\n| ------ | ------ | ----- |\n|200|Success|Retrieved list of user tweets|\n|201|Created|Create new tweet|\n|400|Bad request|Invalid email for registration|\n|401|Unauthorized|No permission or not logged in|\n|500|Error|Exception happened on server|\n\n## Deploying\n\nThe easiest way to deploy your APIs is to use [Heroku](http://heroku.com).\n\n### Register for an account\n\nFirst, register yourself a (free) Heroku account at \u003chttps://api.heroku.com/signup\u003e. This is\nyour developer account that can contain any number of free applications.\n\n### Create app\n\nRun the following command in the terminal to create your app:\n\n```bash\n$ gem install heroku\n$ heroku login\n$ heroku create myappname\n```\n\n**Note:** Be sure to replace `myappname` with your own application name above.\n\nBe sure to enter your username and password as defined when you created your Heroku account earlier.\n\n### Deploy App\n\nNext it is time to deploy your application:\n\n```bash\n$ git push heroku master\n```\n\nYou may need to type 'yes' when it asks if you want to continue. At this point you should see\nHeroku deploying your application to the internet:\n\n```\nWarning: Permanently added the RSA host key for IP address '50.19.85.156' to the list of known hosts.\nCounting objects: 206, done.\nDelta compression using up to 8 threads.\nCompressing objects: 100% (184/184), done.\nWriting objects: 100% (206/206), 53.24 KiB, done.\nTotal 206 (delta 70), reused 0 (delta 0)\n\n-----\u003e Ruby/Rails app detected\n-----\u003e Installing dependencies using Bundler version 1.3.2\n...\n```\n\nWait while this command sets up your application on their servers. Once this is finished, it is time to setup our application on their servers:\n\n### Verify App\n\nNow you can open the url to your app with:\n\n```bash\n$ heroku open\n```\n\nand now you can visit `/api/vi/sessions` in your browser to confirm this app is running if you see:\n\n```\n\"This is a sign that the API endpoints are configured\"\n```\n\n### Wrapping Up ###\n\nAt this point you have a deployed API application. If you make changes to your app, simply run:\n\n```bash\n$ git add .\n$ git commit -am \"describe my changes here\"\n$ git push heroku master\n```\n\nand the updated code will be pushed to Heroku accordingly.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodepath%2Fserver-api-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodepath%2Fserver-api-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodepath%2Fserver-api-template/lists"}