{"id":2113,"date":"2016-07-26T12:06:19","date_gmt":"2016-07-26T10:06:19","guid":{"rendered":"https:\/\/inlab.fib.upc.edu\/?p=2113"},"modified":"2016-07-26T12:06:19","modified_gmt":"2016-07-26T10:06:19","slug":"django-rest-api","status":"publish","type":"post","link":"https:\/\/inlab.fib.upc.edu\/en\/uncategorized-ca\/django-rest-api","title":{"rendered":"Django REST API"},"content":{"rendered":"<p>A very common way of obtaining information from different sources is with a <strong>REST&nbsp;API<\/strong>, which provides different <strong>API endpoints<\/strong> that are accessible in order to get certain data. <strong>Django REST&nbsp;Framework<\/strong> is a framework that allows us to easily create a <strnog>Python REST&nbsp;API. Currently, this technology is used in various projects, such as the <strong>Rac\u00f3<\/strong>&nbsp;API&nbsp;or the <strong><a href=\"http:\/\/inlab.fib.upc.edu\/en\/uoc-index-using-learning-analytics-measure-elearning\" target=\"_blank\" rel=\"noopener\">UOC \u00edndex<\/a><\/strong> project.<\/strnog><\/p>\n<p><!--more--><\/p>\n<h2>Introduction<\/h2>\n<p>A very common way of obtaining information from different sources is with a <strong>REST&nbsp;API<\/strong>, which provides different <strong>API endpoints<\/strong> that are accessible in order to get certain data. <strong>Django REST&nbsp;Framework<\/strong> is a framework that allows us to easily create a <strnog>Python REST&nbsp;API. Currently, this technology is used in various projects, such as the <strong>Rac\u00f3<\/strong>&nbsp;API&nbsp;or the <strong><a href=\"http:\/\/inlab.fib.upc.edu\/en\/uoc-index-using-learning-analytics-measure-elearning\" target=\"_blank\" rel=\"noopener\">UOC \u00edndex<\/a><\/strong> project.<\/strnog><\/p>\n<h2>Installation<\/h2>\n<p>A good practice is to create a <strong>virtual environment<\/strong> with all the requirements to execute the REST&nbsp;API created with Django:<\/p>\n<pre class=\"brush:bash\">\r\n# Create the project directory\r\nmkdir tutorial\r\ncd tutorial\r\n# Create a virtualenv to isolate our package dependencies locally\r\nvirtualenv env\r\nsource env\/bin\/activate # On Windows use `env\\Scripts\\activate`\r\n<\/pre>\n<p>Once we\u2019ve installed the environment, we still need to install the necessary Python <strong>libraries<\/strong> in order to be able to use Django:<\/p>\n<pre class=\"brush:bash\">\r\n# Install Django and Django REST framework into the virtualenv\r\npip install django\r\npip install djangorestframework\r\n# Set up a new project with a single application\r\ndjango-admin.py startproject tutorial . # Note the trailing '.' character\r\ncd tutorial\r\ndjango-admin.py startapp quickstart\r\n<\/pre>\n<p>Now we have everything ready to start our Django project.<\/p>\n<h2>Project structure<\/h2>\n<p>Examining what has been created inside the <code>tutorial<\/code> folder, we can see how a Django project is structured:<\/p>\n<ul>\n<li><code>env<\/code>: virtual environment with the installed libraries and required files for the correct execution of the project.<\/li>\n<li><code>tutorial<\/code>: in this folder we can find the project\u2019s configuration. We want to point out <code>settings.py<\/code> and <code>urls.py<\/code>, files that control the project\u2019s configuration (installed applications, usable modules, supported database types\u2026) and the available urls.<\/li>\n<li><code>quickstart<\/code>: in this folder we can find the quickstart application configuration.<\/li>\n<li><code>manage.py<\/code>: Python executable that allows to launch the API.<\/li>\n<\/ul>\n<h2>Application structure<\/h2>\n<p>Examining what has been created inside the <code>quickstart<\/code> folder, we can see how a Django project is structured:<\/p>\n<ul>\n<li><code>models.py<\/code>: file with information about the data models our application uses.<\/li>\n<li><code>views.py<\/code>: file that contains all the views used by the application.<\/li>\n<li><code>tests.py<\/code>: file to develop tests for the application.<\/li>\n<li><code>migrations<\/code>: directory responsible for detecting changes in the application databases.<\/li>\n<\/ul>\n<p>It\u2019s highly recommended to create additional files, in particular these two:<\/p>\n<ul>\n<li><code>urls.py<\/code>: file with the API\u2019s possible urls or endpoints.<\/li>\n<li><code>queries.py<\/code>: file with the different calls to the databases.<\/li>\n<\/ul>\n<h2>Tutorial<\/h2>\n<p>Once we\u2019re done with the installation as described at the Installation item, we\u2019ll create a new endpoint to describe in more detail how Django works:<\/p>\n<ol>\n<li>We open the file <code>tutorial\/tutorial\/settings.py<\/code> and add the list INSTALLED_APPS \u2018rest_framework\u2019 and \u2018quickstart\u2019.<\/li>\n<li>We open the file <code>tutorial\/tutorial\/urls.py<\/code> and add the following url to the list urlpatterns: url(r\u2019^quickstart\/\u2019, include(\u2018quickstart.urls\u2019)). With this step, we\u2019re done with the basic configuration of our quickstart application.<\/li>\n<li>Now we\u2019ll add our first views to <code>tutorial\/quickstart\/views.py<\/code>:\n<pre class=\"brush:bash\">\r\ndef index(request):\r\n    return HttpResponse(\"Hello, world. You're at the quickstartapp index.\")\r\nclass Example(APIView):\r\n\"\"\"\r\nReturns data from the football player Antoine Griezmann\r\n\"\"\"\r\n    def get(self, request):\r\n        data = {'Player': 'Antoine griezmann','Team': 'Atl\u00e9tico de Madrid', 'Age': 25}\r\n        return HttpResponse(json.dumps(data, indent=4, sort_keys=True), content_type=\"application\/json\")\r\n<\/pre>\n<\/li>\n<li>We go to <code>\/tutorial\/quickstart<\/code> and create the file <code>urls.py<\/code>:\n<pre class=\"brush:bash\">\r\nfrom django.conf.urls import url\r\nfrom . import views\r\nurlpatterns = [\r\n    url(r'^index\/', views.index, ),\r\n    url(r'^griezmann\/', views.Example.as_view(), name=\"'example'),\r\n]\r\n<\/pre>\n<\/li>\n<li>We go to <code>\/tutorial<\/code> and execute <code>python manage.py runserver<\/code> (it runs on port 8000 by default) and we verify our new enpoint is functioning. When calling the endpoint http:\/\/localhost:8000\/quickstart\/griezmann\/ we should get a result similar to this one:<br \/>\n\t{<br \/>\n\t&#8220;Age&#8221;: 25,<br \/>\n\t&#8220;Player&#8221;: &#8220;Antoine Griezmann&#8221;,<br \/>\n\t&#8220;Team&#8221;: &#8220;Atletico de Madrid&#8221;<br \/>\n\t}<\/li>\n<\/ol>\n<p>This is only a small example where the data is generated every time we access the corresponding view. If we created a queries.py file, we\u2019d be able to define a more complex way of obtaining the data, so that each time a certain view were called the corresponding data would be looked for at a given database.<\/p>\n<h2>To summarize<\/h2>\n<p>We\u2019ve seen how to start developing a Django REST&nbsp;API that allows for a very simple development but at the same time powerful and easily scalable. You can find the official framework documentation at: <a href=\"http:\/\/www.django-rest-framework.org\/\" target=\"_blank\" rel=\"noopener\">http:\/\/www.django-rest-framework.org\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A very common way of obtaining information from different sources is with a REST&nbsp;API, which provides different API endpoints that are accessible in order to get certain data. Django REST&nbsp;Framework is a framework that allows us to easily create a Python REST&nbsp;API. Currently, this technology is used in various projects, such as the Rac\u00f3&nbsp;API&nbsp;or the [&hellip;]<\/p>\n","protected":false},"author":594,"featured_media":2108,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"experteses":[16,26],"class_list":["post-2113","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized-ca","experteses-ictenvironmentsandservicestosupportlearning-en","experteses-knowledgeandserviceengineering-en"],"acf":[],"_links":{"self":[{"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/posts\/2113","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/users\/594"}],"replies":[{"embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/comments?post=2113"}],"version-history":[{"count":0,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/posts\/2113\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/media\/2108"}],"wp:attachment":[{"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/media?parent=2113"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/categories?post=2113"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/tags?post=2113"},{"taxonomy":"experteses","embeddable":true,"href":"https:\/\/inlab.fib.upc.edu\/en\/wp-json\/wp\/v2\/experteses?post=2113"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}