Complete Download (Ebook PDF) Django For APIs: Build Web APIs With Python and Django PDF All Chapters
Complete Download (Ebook PDF) Django For APIs: Build Web APIs With Python and Django PDF All Chapters
com
https://ebooksecure.com/product/ebook-pdf-django-
for-apis-build-web-apis-with-python-and-django/
https://ebooksecure.com/product/ebook-pdf-django-for-professionals-
production-websites-with-python-django/
ebooksecure.com
https://ebooksecure.com/product/ebook-pdf-web-development-and-design-
foundations-with-html-7th/
ebooksecure.com
https://ebooksecure.com/product/ebook-pdf-econometrics-by-example-2nd-
edition/
ebooksecure.com
(eBook PDF) Real-Life Sociology: A Canadian Approach 2nd
Edition
https://ebooksecure.com/product/ebook-pdf-real-life-sociology-a-
canadian-approach-2nd-edition/
ebooksecure.com
https://ebooksecure.com/product/ebook-pdf-financial-and-managerial-
accounting-3rd-edition-by-jerry-j-weygandt/
ebooksecure.com
https://ebooksecure.com/product/ebook-pdf-reading-literature-and-
writing-argument-6th-edition/
ebooksecure.com
https://ebooksecure.com/product/ebook-pdf-linguistic-genocide-in-
education-or-worldwide-diversity-and-human-rights/
ebooksecure.com
https://ebooksecure.com/download/comm-mindtap-course-list-6th-edition-
ebook-pdf/
ebooksecure.com
(eBook PDF) Social Marketing MKT3SEM (Custom Edition )
https://ebooksecure.com/product/ebook-pdf-social-marketing-mkt3sem-
custom-edition/
ebooksecure.com
Django for APIs
Build web APIs with Python and Django
William S. Vincent
1
Table of Contents
Introduction
Prerequisites
Why APIs
Django REST Framework
Why this book
Conclusion
2
Initial Set Up
Models
Django REST Framework
URLs
Serializers
Views
Consuming the API
Browsable API
CORS
Tests
Conclusion
Chapter 6: Permissions
Create a new user
Add log in to the browsable API
AllowAny
View-Level Permissions
Project-Level Permissions
Custom permissions
Conclusion
3
Basic Authentication
Session Authentication
Token Authentication
Default Authentication
Implementing token authentication
Endpoints
Django-Rest-Auth
User Registration
Tokens
Conclusion
Conclusion
Next Steps
Giving Thanks
4
Introduction
The internet is powered by RESTful APIs. Behind the scenes
even the simplest online task involves multiple computers
interacting with one another.
In this book you will learn how to build multiple RESTful web APIs
of increasing complexity from scratch using Django and Django
REST Framework.
Prerequisites
If you’re brand new to web development with Django, I
recommend first reading my previous book Django for Beginners.
The first several chapters are available for free online and cover
proper set up, a Hello World app, Pages app, and a Message
Board website. The full-length version goes deeper and covers a
Blog website with forms and user accounts as well as a
production-ready Newspaper site that features a custom user
model, complete user authentication flow, emails, permissions,
and more.
5
This background in traditional Django is important since Django
REST Framework deliberately mimics many Django conventions.
Why APIs
Django was first released in 2005 and at the time most websites
consisted of one large monolithic codebase. The “back-end”
consisted of database models, URLs, and views which interacted
with the “front-end” templates of HTML, CSS, and JavaScript that
controlled the presentational layout of each web page.
6
years to come, the back-end API can remain the same. No major
rewrite is required.
7
it can transform any existing Django application into a web API.
This book is the guide I wish existed when starting out with
Django REST Framework.
Conclusion
Django and Django REST Framework is a powerful and
accessible way to build web APIs. By the end of this book you will
be able to build your own web APIs from scratch properly using
modern best practices. And you’ll be able to extend any existing
Django website into a web API with a minimal amount of code.
Let’s begin!
8
Chapter 1: Web APIs
Before we start building our own web APIs it’s important to review
how the web really works. After all, a “web API” literally sits on top
of the existing architecture of the world wide web and relies on a
host of technologies including HTTP, TCP/IP, and more.
9
Visit https://testbankfan.com
now to explore a rich
collection of testbank or
solution manual and enjoy
exciting offers!
links (hyperlinks) to other documents, could be moved onto the
internet.
Today, when most people think of “the internet,” they think of the
World Wide Web, which is now the primary way that billions of
people and computers communicate online.
URLs
A URL (Uniform Resource Locator) is the address of a resource
on the internet. For example, the Google homepage lives at
https://www.google.com.
When you want to go to the Google homepage, you type the full
URL address into a web browser. Your browser then sends a
request out over the internet and is magically connected (we’ll
cover what actually happens shortly) to a server that responds
with the data needed to render the Google homepage in your
browser.
10
Many webpages also contain an optional path, too. If you go to
the homepage for Python at https://www.python.org and click on
the link for the “About” page you’ll be redirected to
https://www.python.org/about/. The /about/ piece is the path.
a scheme - https
a hostname - www.python.org
and an (optional) path - /about/
After the browser has the IP address for a given domain, it needs
a way to set up a consistent connection with the desired server.
This happens via the Transmission Control Protocol (TCP) which
provides reliable, ordered, and error-checked delivery of bytes
between two application.
11
2. The server responds with a SYN-ACK acknowledging the
request and passing a connection parameter
3. The client sends an ACK back to the server confirming the
connection
HTTP Verbs
Every webpage contains both an address (the URL) as well as a
list of approved actions known as HTTP verbs. So far we’ve
mainly talked about getting a web page, but it’s also possible to
create, edit, and delete content.
Consider the Facebook website. After logging in, you can read
your timeline, create a new post, or edit/delete an existing one.
These four actions Create-Read-Update-Delete are known
colloquially as CRUD functionality and represent the
overwhelming majority of actions taken online.
Endpoints
A website consists of web pages with HTML, CSS, images,
JavaScript, and more. But a web API has endpoints instead which
are URLs with a list of available actions (HTTP verbs) that expose
12
data (typically in JSON, which is the most common data format
these days and the default for Django REST Framework).
We will become much more familiar with API endpoints over the
course of this book but ultimately creating an API involves making
a series of endpoints: URLs with associated HTTP verbs.
HTTP
We’ve already talked a lot about HTTP in this chapter, but here we
will describe what it actually is and how it works.
13
server is some special software and a persistent internet
connection.
The top line is known as the request line and it specifies the HTTP
method to use (GET), the path (/), and the specific version of HTTP
to use (HTTP/1.1).
The two subsequent lines are HTTP headers: Host is the domain
name and Accept_Language is the language to use, in this case
American English. There are many HTTP headers available.
Hello, world!
The top line is the response line and it specifies that we are using
HTTP/1.1. The status code 200 OK indicates the request by the
client was successful (more on status codes shortly).
14
Exploring the Variety of Random
Documents with Different Content
“Wall, wall! I never seen two bodies with one head till now. Why,
it’s Master Dave! and his female bride!”
The farmer’s wife cackled at the wit of her spouse, and Patty
giggled with well-bred reserve. She treated the old rustics with the
manner she held toward the blacks who had been her father’s slaves
when she was younger. But though the Albesons were quick to
remind any presumptuous prigs that they were as good as royalty in
the great and only republic, they found Patty’s tyranny as pretty as a
baby’s.
They led the way into the house. David’s black man Cuff took the
horses to the stable, and Patty’s brown woman Teen carried the
luggage up the steps and up the stairs to the long, lone room under
the eaves, that grazed the four high tops of bedposts carved as if
the mahogany had been twisted or braided.
The first duty was to wash off the dust of the travel. When Patty
lifted the scuttle hat from the clutter of her curls before the mirror,
she screamed with dismay:
“I’m blacker than Teen!”
RoBards himself poured water into the bowl and boasted of its
clarity.
“Not much like the soup you get from your city cisterns, eh?”
“It’s cold, though,” she murmured.
She put him out of the room while she changed her dress to a
simple, loose house-robe. She slipped out of the steel cuirass of her
stays, and the soft sleeves drooped from her shoulders along her
arms. There was a girl’s body bewitchingly hinted inside the
twinkling wrinkles.
After the return to simple, clinging things of the brief French
republic and the early Empire, the fashions had been departing more
and more from any respect for God’s image beneath. When Patty
came down the steps in something that was rather drapery than a
group of balloons, RoBards was amazed to find how human she was
after all, how Grecian, somehow; how much quainter, littler, dearer.
She apologized for her immodesty, but gave weariness as her
excuse.
“I should have fainted in my room—if you had been there,” she
said, with an audacity he had never dreamed her capable of. “But
where’s the profit of a swoon if you fall into the arms of another
woman—and a black one at that?”
“You don’t have to faint to get into my arms,” he riposted as he
crushed her close.
“I’ll faint if you don’t let me out of them, Mist’ RoBards,” she
gasped.
Then they went in to tea. She made hardly a pretence of eating.
Even if she had not been trained to fast at table like a lady, she
would have been too jaded with the travel.
Afterward he walked with her on the narrow piazza in the rising
moon, and he felt so wonderfully enriched by her possession, so
intimately at home with her, that he asked her if he might smoke.
“I beg you to, Mist’ RoBards,” she said; “I love the flavor of
Havana.”
He took from the portmanteau-like lining of his hat one of the
cigars he carried there with his red silk handkerchief, his black
gloves, and any other small baggage that might otherwise bulge his
pockets. As he lighted it with one of the new spiral sulphur matches,
he remembered that Harry Chalender had smoked much and
expensively.
Harry Chalender even smoked cigars on the street and in office
hours, though no gentleman was supposed to do that, and it would
have ruined a less secure young man financially and socially. Some
of the banks would not lend money to a man eccentric enough to
smoke on the street or to wear a mustache. But Harry had dared
even to grow and wear a mustache down Broadway. It was to pay a
bet on an election, but it shocked the more conservative.
His only effeminacy was his abstention from chewing tobacco and
from snuff. Patty often praised him for not spitting tobacco juice
about over her skirts and carpets, as so many of the gentlemen did.
She had one dress quite ruined on Broadway by a humorist’s
ejaculation of such liquor.
Because of Chalender, RoBards flung down his cigar and glared at
it where it lay in the grass, as smouldering as his sullen jealousy,
and glared back like an eye, watchful and resentful.
Only a little while he was privileged to stroll his porch with his arm
about Patty Jessamine’s unfortressed waist, for she tried to smuggle
away a yawn under the cover of a delicious sigh, and then protested
that she could not keep her eyelids open.
“No wonder!” he answered, “they’re so big!”
She kissed him on the cheek and drifted away before he could
retaliate. He walked up and down alone a while, breathing the
incense of her possession in the quiet air, still faintly flavored with
the perfume she employed.
Then he went in and up the dark stairs to find her. She lay asleep
along the bed as if she had been flung there. She was lying across
the border of the candle’s yellow feud with the blue moonlight; they
divided her form between dim gold and faint azure. She had fallen
aslumber where she fell, and he stole close to wonder over her and
to study her unblushing beauty.
Her face was out of the reach of the candle’s flickering gleam, and
the moon bewitched it with a mist of sapphire. Through the open
window a soft breeze loitered, fingering her curls, lifting them from
her snowy neck and letting them fall. And from the tulip tree a long,
low branch, studded with empty sconces of living brass, beat upon
the pane with muffled strokes.
“Beautiful! beautiful!” he whispered—not to her, nor to himself, but
to a something that seemed to watch with him. He longed to be
worthy of such beauty, and wondered if she—the she inside that
little bosom—were worthy of such treasures, such perils, as her face
and her fascinations.
His heart ached with a yearning to shelter her from the evil of the
world, the plagues that would rend that lacy fabric, the fiends that
would soil its cleanliness. Such a petulant, froward, reckless little imp
it was that dwelt inside the alabaster shrine! Such loyalty she had for
the gaudy city and its frivolities! Such terror of the pestilence, yet
such terror of the great, sweet loneliness of this beloved solitude!
Else, why had she stared back along the road with a sorrow, with
a regret that seemed to trail almost like a ribbon reaching all the
way to town? Would she ever be divorced from the interests that he
could neither understand nor admire?
Well, she was his for a while—for now—and more his own while
she slept than while she was awake, for when she was awake her
eyes kept studying the plain, dull walls, and his plain, dull self;
wondering, no doubt, what substitute he could provide for the
dances and picnics and romances that crowded the days and nights
in the city.
He bent to kiss a cheek like warm and pliant porcelain, and to
draw the quilt across a shoulder escaped from its sleeve, and all
aglow, as if light itself slumbered there.
He tiptoed from the room and down the stairs and into the August
night. He stepped into a cataract of moonbeams streaming down
upon the breathing grass and the somnolent trees, the old walls and
fences, and the waft flowers in the unkempt garden.
A wind walked to and fro among them like a prisoner in trailing
robes, a wind that seemed to be trying to say something, and could
not, because its tongue had been plucked out. But it kept trying
inarticulately to mumble a warning—against what?—the hazards of
life and love perhaps, and the inevitable calamities that follow
success.
He had succeeded in winning Patty Jessamine. But what else had
he incurred?
CHAPTER III
BY and by the summer sifted from the trees and ebbed from the sky.
The honeymoon passed like a summer, in days and nights of hot
beauty, in thunder-salvos of battle, in passions of impatient rain.
For a while the autumn was a greater splendor, a transit from a
green earth starred with countless blossoms of scarlet, purple,
azure, to a vast realm of gold—red gold, yellow gold, green gold, but
always and everywhere gold. All Westchester was a treasure-temple
of glory. Then the grandeur dulled, the gold was gilt, was only
patches of gilt, was russet, was shoddy. The trees were bare. Sharp
outlines of unsuspected landscape came forth like hags whose robes
have dropped from their gaunt bones. The wind grew despondent.
Savor went with color; hope was memory; warmth, chill.
Something mournful in the air reminded RoBards of a poem that
Mr. Bryant, the editor of the Post, had written a few years before:
When he quoted this to Patty, her practical little soul was moved,
as always, to the personal:
“Your Mr. Bryant writes better than he fights, Mist’ RoBards. Only
last year, almost in front of our house, I saw him attack Mr. Stone, of
the Commercial Advertiser, with a horsewhip. Mr. Stone carried off
the whip. It was disgusting, but it brightened Broadway. Oh, dear,
does nothing exciting ever happen up here? Wouldn’t it be wonderful
to stroll down to the Battery to watch the sunset and cross the
bridge to Castle Garden, and hear the band play, and talk to all our
friends? And go to a dance, perhaps, or a theatre? The Kembles are
there setting the town on fire! And am I never to dance again? I was
just learning to waltz when the cholera came. I sha’n’t be able to
dance at all unless we go at once.”
It shocked RoBards to think that marriage had not changed the
restless girl to a staid matron. That she should want to waltz was
peculiarly harrowing, for this new and hideously ungraceful way of
jigging and twisting was denounced by all respectable people as a
wanton frenzy, heinously immoral, indecently amorous, and lacking
in all the dignity that marked the good old dances.
But he was in a mood to grant her anything she wished. She had
a right to her wishes now, for she was granting him his greatest
wish; a son and heir was mystically enfolded in her sweet flower-
flesh, as hidden now as the promise of the tulip tree in a bud that
hardly broke the line of a bough in the early spring, but later slowly
unsheathed and published the great leaf and the bright flower.
So he bade the servants pack her things and his, and they set out
again for New York.
Now the tide flowed back with them as it had ebbed with them.
The exiles were flocking once more to the city, and new settlers
were bringing their hopes to market. A tide of lawyers and
merchants was setting strong from New England, and packs of
farmers who had harvested only failure from the stingy lands,
counted on somehow winnowing gold on the city streets, where
sharpers and humbugs of every kind would take from them even
that which they had not.
The drive to New York was amazingly more than a mere return
along a traveled path. Though they had gone out in a panic, they
had been enveloped in a paradise of leaves and flowers and lush
weeds, as well as in a bridal glamor. Now they went back under
boughs as starkly bare as the fences of rail or stone; only the weeds
bore flowers, and those were crude of fabric as of hue. And the
hearts of the twain were already autumnal. Their April, June, and
August of love were gone and November was their mantle. Patty’s
orange blossoms were shed, and they had been artificial, too.
Below White Plains the road was a-throng with cattle that
frightened Patty and the horses. When they were clear of these
moving shoals, they came into the Post Road where the stages went
like elephants in a panic. But Patty found them beautiful. She
rejoiced in the increasing crowds, and as the houses congregated
about her, and the crowded streets accepted her, she clapped her
hands and cried:
“How good it is to be home!”
This sent a graveyard chill through RoBards’ heart, for it meant
that home to her was not in the solitude of his heart, but in the
center of the mob.
Home was to her more definitely the house in Park Place, her
father’s house to which he must take her till he found another
lodging. Her father and mother greeted her as a prodigal and him as
a mere body servant—which was what he felt himself to be.
The chief talk was of the cholera and its havoc. Three thousand
and five hundred dead made up its toll in the city, but the menace
was gone, and those who lived were doubly glad. The crowds in the
streets showed no gaps; there were no ruins visible. New houses
were going up, narrow streets being widened and the names
changed.
It was only when the Sabbath called them to church, or some
brilliant performance took them to see Fanny Kemble and her father
at the Park Theatre, and they inquired for one friend or another, that
they learned dreadfully how many good friends had been hurried
feet first to Washington Square, whence they would never return.
Dinners were few, since nearly every family wore mourning for
someone; but gradually the gayety returned in full sweep. The dead
were forgotten, and the plans for preventing a return of the plague
were dismissed as a tiresome matter of old-fashioned unimportance.
The pumps and cisterns were no longer blamed for the slaughter of
the innocents.
And now Patty must go into eclipse gradually. She grew more and
more peevish. When she complained that everybody worth while
was moving uptown, RoBards bought a house in St. John’s Park, just
south of Canal Street, and only a little distance from the Hudson
River. The house was new and modern, with a new cistern in the
rear. Only a few steps away was a pump supplied with water from
the new city water works in the salubrious region of Thirteenth
Street and Broadway. There was a key that admitted the family to
the umbrageous park, behind whose high fence there was seclusion.
There was something aristocratic and European, too, about the
long iron rail fence that framed the entire square, the same in front
of every house, and giving them all a formal uniform, a black court
dress.
But even aristocracy palled. Patty found but a brief pleasure in the
privilege of walking there at twilight, and she dared not venture out
before dusk. It was chill then and she shivered as she sat on a
bench and breathed in the gloom that drooped from the naked
branches like a shroud. She did not want to be a mother yet, and
she faced the ordeal with dread, knowing how many mothers die,
how few babies lived, for all the pain of their long preparation.
The winter was cold and she complained of the dark of nights,
though her husband multiplied the spermaceti candles and the astral
lamps till her room was as dazzling as an altar. He filled the bins in
the hall closet with the best Liverpool coal and kept the grates
roaring. But she wailed of mornings when he had to break the ice in
the water pitcher for her and she huddled all day by the red-hot iron
stove. She made her servants keep it charged with blazing wood,
until RoBards was sure that the house would be set on fire.
When spring came again and released grass, birds, trees, souls,
flowers, the very air from the gyves of winter, she was so much
more a prisoner that she herself pleaded to be taken back to
Tuliptree Farm. If she could not meet people she did not want to see
them pass her windows, or hear them laugh as they went by in
shadows of evening time. On the farm she could wander about the
yard unterrified and, with increasing heaviness, devote herself to the
flowerbeds. She fled at the sight of any passerby and was altogether
as hidden and craven as only a properly bred American wife
undergoing the shameful glory of motherhood could be.
She was smitten at times with panics of fear. She knew that she
would perish and she called her husband to save her from dying so
young; yet when he got her in his arms to comfort her, she called
him her murderer. She accused him of dragging her into the hasty
marriage, and reminded him that if he had not inflicted his ring and
his name and his burden upon her she could have gone with her
father and mother this summer to Ballston Spa, where there was life
and music, where the waltz flourished in rivalry with the vivacious
polka just imported.
But even in her most insane onsets she did not taunt him now
with the name of Harry Chalender. That was a comfort.
One day Chalender drove up to the house, but she would not see
him. Which gave RoBards singular pleasure. Chalender lingered,
hoping no doubt that she would relent. He sat out an hour, drinking
too much brandy, and cursing New York because it laughed at his
insane talk of going forty miles into the country to fetch a river into
the city. Chalender wanted to pick up the far-off Croton and carry it
on a bridge across the Spuyten Duyvil!
When he had left, Patty, who had overheard his every sentence,
said: “He must be going mad.” She was absent in thought a while,
then murmured as if from far off:
“I wonder if he is drinking himself to death on purpose, and why?”
CHAPTER V