restful examples · 2019-02-16 · python/django example from rest_framework.views import apiview...

15
RESTful Examples RESTful Examples __________________________________________________________ 1 Apache ____________________________________________________________________ 3 Jersey _____________________________________________________________________ 5 JAX-RS ____________________________________________________________________ 7 ApplicationConfig.java____________________________________________________________________7 HelloGregg.java _________________________________________________________________________8 REST in JavaScript _________________________________________________________ 9 #1) createRequest with XMLHttpRequest ___________________________________________________9 #2) Must supply a Callback function onreadystatechange _____________________________________9 #3) Sending the Request ________________________________________________________________10 Python/Django ____________________________________________________________ 11 .user __________________________________________________________________________________11 .auth __________________________________________________________________________________11 Standard HttpRequest attributes __________________________________________________________11 Responses ____________________________________________________________________________11 Creating Responses ____________________________________________________________________11 Class Based Views _____________________________________________________________________11 Python/Django Example _________________________________________________________________12 Testing our PYTHON API ________________________________________________________________12 Or directly through the browser...__________________________________________________________13 Types of Routers _______________________________________________________________________14 Serialization and Deserialization important parts of Django-rest -framework _____________________14 Requests and Responses________________________________________________________________14 Request objects:________________________________________________________________________14 Issuing GET Requests __________________________________________________________________14 Issuing POST Requests _________________________________________________________________14

Upload: others

Post on 29-May-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

RESTful Examples RESTful Examples __________________________________________________________ 1

Apache ____________________________________________________________________ 3

Jersey _____________________________________________________________________ 5

JAX-RS ____________________________________________________________________ 7 ApplicationConfig.java ____________________________________________________________________ 7 HelloGregg.java _________________________________________________________________________ 8

REST in JavaScript _________________________________________________________ 9 #1) createRequest with XMLHttpRequest ___________________________________________________ 9 #2) Must supply a Callback function onreadystatechange _____________________________________ 9 #3) Sending the Request ________________________________________________________________ 10

Python/Django ____________________________________________________________ 11 .user __________________________________________________________________________________ 11 .auth __________________________________________________________________________________ 11 Standard HttpRequest attributes __________________________________________________________ 11 Responses ____________________________________________________________________________ 11 Creating Responses ____________________________________________________________________ 11 Class Based Views _____________________________________________________________________ 11 Python/Django Example _________________________________________________________________ 12 Testing our PYTHON API ________________________________________________________________ 12 Or directly through the browser...__________________________________________________________ 13 Types of Routers _______________________________________________________________________ 14 Serialization and Deserialization important parts of Django-rest-framework _____________________ 14 Requests and Responses ________________________________________________________________ 14 Request objects:________________________________________________________________________ 14 Issuing GET Requests __________________________________________________________________ 14 Issuing POST Requests _________________________________________________________________ 14

Page 2: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

REST in Java Simple REST client in Java

3 methods 1) Apache HttpClient 2) Jersey 3) JAX-RS (Java API for RESTful Web Services)

Page 3: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

Apache

HTTP GET method:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet('http://restUrl'); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } }

HTTP POST method; for sending simple string

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost('http://restUrl'); StringEntity input = new StringEntity('product'); post.setEntity(input); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } }

Page 4: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

For JSON you can use JSONObject to create string representation of JSON.

JSONObject json = new JSONObject(); json.put('name', 'value'); json.put('name', 'value'); StringEntity se = new StringEntity( json.toString());

POST request with multiple parameters:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost('http://restUrl'); List nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair('name', 'value')); //you can as many name value pair as you want in the list. post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ''; while ((line = rd.readLine()) != null) { System.out.println(line); } } }

Page 5: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

Jersey

the specification of REST support in Java. Jersey contains basically a REST server and a REST client. i

HTTP GET method: import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri('http://restUrl').build()); // getting XML data System.out.println(service. path('restPath').path('resourcePath'). accept(MediaType.APPLICATION_JSON).get(String.class)); // getting JSON data

System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class));

} }

HTTP POST method:

import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.core.util.MultivaluedMapImpl; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource webResource = client.resource(UriBuilder.fromUri('http://restUrl').build()); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add('name', 'val'); formData.add('name', 'val'); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .post(ClientResponse.class, formData); System.out.println('Response ' +

Page 6: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

response.getEntity(String.class)); } }

POST request , Form class submit multiple parameters:

import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.apache.http.client.ClientProtocolException; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.representation.Form; public class Test { public static void main(String[] args) throws ClientProtocolException, IOException { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(UriBuilder.fromUri('http://restUrl').build()); Form form = new Form(); form.add('name', 'value'); form.add('name', 'value'); ClientResponse response = service.path('restPath').path('resourcePath'). type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form); System.out.println('Response ' + response.getEntity(String.class)); } } Posted by: Harsh Raval in Enterprise Java September 11th, 2012

Page 7: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

JAX-RS ApplicationConfig.java

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package helloGregg; import java.util.Set; import javax.ws.rs.core.Application; /** * * @author owner */ @javax.ws.rs.ApplicationPath("webresources") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new java.util.HashSet<>(); addRestResourceClasses(resources); return resources; } /** * Do not modify addRestResourceClasses() method. * It is automatically populated with * all resources defined in the project. * If required, comment out calling this method in getClasses(). */ private void addRestResourceClasses(Set<Class<?>> resources) { resources.add(helloGregg.HelloGregg.class); } }

Page 8: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

HelloGregg.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package helloGregg; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.ws.rs.core.MediaType; /** * REST Web Service * * @author owner */ @Path("helloGregg") public class HelloGregg { @Context private UriInfo context; /** * Creates a new instance of HelloGregg */ public HelloGregg() { } /** * Retrieves representation of an instance of helloGregg.HelloGregg * @return an instance of java.lang.String */ @GET @Produces(MediaType.TEXT_HTML) public String getHtml() { return "<html><body><h1>Hello, Gregg!!</h1>RESTful using javax.ws.rs, RESTful Java API</body></html>";} /** * PUT method for updating or creating an instance of HelloGregg * @param content representation for the resource */ @PUT @Consumes(MediaType.TEXT_HTML) public void putHtml(String content) { } }

Page 9: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

REST in JavaScript XMLHttpRequest object allows you to send a request, either GET or POST; client-side (in-browser)

JavaScript.

AJAX applications are RESTful, every AJAX request is an HTTP request,

Creating XMLHttpRequest Objects Create request, create callback function then issue the actual GET or POST #1) createRequest with XMLHttpRequest

no standard way to create XMLHttpRequest objects allows you to send a request, either GET or POST.

cross-browser solution: Diff for each Browser…

function () { var result = null; if (window.XMLHttpRequest) { // FireFox, Safari, etc. result = new XMLHttpRequest(); if (typeof xmlhttp.overrideMimeType != 'undefined') { result.overrideMimeType('text/xml'); // Or anything else } } else if (window.ActiveXObject) { // MSIE result = new ActiveXObject("Microsoft.XMLHTTP"); } else { // No known mechanism -- consider aborting the application } return result; }

#2) Must supply a Callback function onreadystatechange

XMLHttpRequest does not immediately return a value. Rather, you have to supply

a callback function createRequest that will be invoked when the request completes. Confusingly, you callback is actually invoked several times (up to four times,

depending on the browser), during different stages of the client/server interaction. It is only the fourth and final stage that interests us;

var req = createRequest(); // defined above // Create the callback: req.onreadystatechange = function() { if (req.readyState != 4) return; // Not there yet if (req.status != 200) { // Handle request failure here... return; } // Request successful, read the response var resp = req.responseText; // ... and use it as needed by your app. }

Note that if the response is an XML response (denoted by the server using MIME type text/xml), it can also be read using the responseXML property. This property

contains an XML document, and can be used as such using JavaScript's DOM

Page 10: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

navigation facilities. #3) Sending the Request

Once we have created the request object and set up its callback function, it is time to issue the request:

req.open("GET", url, true); req.send(); For POST requests, use: req.open("POST", url, true); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(form-encoded request body);

Page 11: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

Python/Django

Authentication

Use different authentication policies for different parts of your API.

Provide both user and token information associated with the incoming request.

.user

request.user typically returns an instance of

django.contrib.auth.models.User,

although the behavior depends on the authentication policy being used. If the request is unauthenticated the default value of request.user is an instance

of django.contrib.auth.models.AnonymousUser.

.auth

request.auth returns any additional authentication context

.method

request.method returns the uppercased string representation of the request's

HTTP method.

Standard HttpRequest attributes

Request extends Django's HttpRequest,

all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.

Responses

Response class

which allows you to return content that can be rendered into multiple content types, depending on the client request. Response class subclasses Django's SimpleTemplateResponse. Response

objects are initialised with data, which should consist of native Python primitives. Creating Responses

Unlike regular HttpResponse objects,

you do not instantiate Response objects with rendered content.

Instead you pass in unrendered data, which may consist of any Python primitives. Class Based Views

APIView class, which subclasses Django's View class.

APIView classes are different from regular View classes in the following ways: Requests passed to the handler methods will be REST framework's Request instances, not Django's

HttpRequest instances.

Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will

manage content negotiation and setting the correct renderer on the response

Page 12: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

Python/Django Example

from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames)

Testing our PYTHON API We're now ready to test the API we've built. Let's fire up the server from the command line.

python ./manage.py runserver

We can now access our API, both from the command-line, using tools like curl... bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ { "count": 2, "next": null, "previous": null, "results": [ { "email": "[email protected]", "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" }, { "email": "[email protected]", "groups": [ ], "url": "http://127.0.0.1:8000/users/2/", "username": "tom" } ] }

Or using the httpie, command line tool... bash: http -a username:password http://127.0.0.1:8000/users/

HTTP/1.1 200 OK ... { "count": 2, "next": null, "previous": null, "results": [ { "email": "[email protected]",

Page 13: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

"groups": [], "url": "http://localhost:8000/users/1/", "username": "paul" }, { "email": "[email protected]", "groups": [ ], "url": "http://127.0.0.1:8000/users/2/", "username": "tom" } ] }

Or directly through the browser...

Page 14: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

Django REST framework (DRF) - REST adds support for auto URL routing to Django

Types of Routers

Simple

Default

Custom

Serialization and Deserialization important parts of Django-rest-framework

1. Serializing data with JSONRenderer: process of making a streamable representation

A JSONRenderer converts the request data into JSON using utf-8 encoding. Normally we use this when we want our data to be streamable.

>>> data

{'cal_id': u'2', 'username': u'tester'}

>>> content = JSONRenderer().render(data)

>>> content

'{"cal_id": "2", "username": "tester"}'

2. Deserializing data with JSONParser:

A JSONParser parses the JSON request content. building an API we render data into JSON format. Firstly, we parse a stream into Python native datatypes with BytesIO

>>> content

'{"cal_id": "2", "username": "tester"}'

>>> stream = BytesIO(content)

>>> data = JSONParser().parse(stream)

>>> data

{u'username': u'tester', u'cal_id': u'2'}

Requests and Responses Request objects:

The request object in REST framework has more abilities. request.DATA in Request object is similar to Request.POST added with the capabilities of handling arbitrary

data which works for 'POST', 'PUT' and 'PATCH' methods.

request.FILES, request.QUERY_PARAMS, request.parsers, request.stream which will help in dealing

with the request a hassle free task.

REST in Python Issuing GET Requests

The Python module urllib2 makes reading URLs trivial: import urllib2 url = 'http://www.acme.com/products/3322' response = urllib2.urlopen(url).read()

Issuing POST Requests A POST request is just as easy, simply passing (encoded) request data as an extra

parameter to urlopen, thus:

import urllib import urllib2

Page 15: RESTful Examples · 2019-02-16 · Python/Django Example from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication,

url = 'http://www.acme.com/users/details' params = urllib.urlencode({ 'firstName': 'John', 'lastName': 'Doe' }) response = urllib2.urlopen(url, params).read()